#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
//ask user for input
string s = get_string();
//make sure get_string() returned a string
if(s != NULL)
{
//iterate over the characters one at a time
for(int i = 0, int n = strlen(s); i < n; i++)
{
//print i'th character in s
printf("%c\n", s[i]);
}
}
else
{
//tell the user that their input is not a string
printf("Sorry, no good\n");
}
}
The compiler complained about this line:
for(int i = 0, int n = strlen(s); i < n; i++)
because I declared the integer n
with int
to define the type.
The program compiles just fine with:
for(int i = 0, n = strlen(s); i < n; i++)
Why is int
required/good form for i
, but not for n
in this example?
It's because this line:
int i = 0, n = strlen(s)
creates two integers called i
and n
and initialises them.
When you put:
int i = 0, int n = strlen(s)
You create an int called i
and initialise it, and then you attempt to create another int called int n
which doesn't make sense.
There's no reason to initialise n
where it is - it shouldn't change, after all. Initialise it before the loop:
int n = strlen(s);
for(int i = 0; i < n; i++)
{
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With