Search code examples
cstringintegercs50

CS50 Week 2 Practice


I am getting an undeclared identifier error for the string text although I identified it previously.

I am trying to create the for loop to run between 0 and strlen(text). Does anyone know what I am missing?

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])

{
    int key = atoi(argv[1]);

    printf("%i\n", key);

    if (argc != 2)
    {
        printf("Usage: ./ceasar key\n");
    }

    else
    {
        string text = get_string("Plaintext: ");
    }

    for (int i = 0, len = strlen(text); i < len; i++)
    {

    }
}

Solution

  • Your "string text" variable is only getting defined within the else statement, so you need to move your for loop into the same else statement:

    
        int main(int argc, string argv[])
        
        {
        
            int key = atoi(argv[1]);
        
            printf("%i\n", key);
        
            if (argc != 2)
            {
                printf("Usage: ./ceasar key\n");
            }
        
            else
            {
                string text = get_string("Plaintext: ");
        
                for(int i = 0, len = strlen(text); i < len; i++)
                {
        
                }
            }
        }