简体   繁体   中英

String Only recording first word

I am just getting started with programming in C and am writing a cypher/decypher program. The user is asked to type in a phrase which is stored as a char *. Problem is the program is only storing the first word of the string and then ignores everything after it. Here's the part of the code that fetches the string and then analyses it

int maincalc(int k)                         //The Calculation Function for Cyphering
{
    char *s;
    s=(char*) malloc(sizeof(100));
    printf("Please enter the phrase that you would like to code: ");  
    fscanf(stdin,"%s %99[^\n]", s);
    int i=0;
    int n=strlen(s);

    while(i<n)
    {
        if(s[i]>=65&&s[i]<=90)              //For Uppercase letters
        {
            int u=s[i];
            int c=uppercalc(u,k);
            printf("%c",c);
        }
        else if(s[i]>=97&&s[i]<=122)    //For Lowercase letters
        {
            int u=s[i];
            int c=lowercalc(u,k);
            printf("%c",c);
        }
        else 
            printf("%c",s[i]);          //For non letters
        i++;
    }
    free(s);
    printf("\n");
    return 0;
} 

Just need to know what to do to get the program to acknowledge the presence of the entire string not only the first word. Thanks

Nope, neither one works. using fscanf doesn't wait for user input. It simply prints "Please enter the phrase..." And then quits fgets also does the same thing, program doesn't wait for an input, just prints "PLease enter..." and then quits.

In that comment, before the edit, you mentioned some previous input. My psychic debugging powers tell me that there is a newline from the previous input still in the input buffer. That would make

fgets(s, 100, stdin);

and

fscanf(stdin, "%99[^\n]", s);

immediately return because they immediately encounter the newline that signals the end of input.

You need to consume the newline from the buffer before getting more string input. You could use

fscanf(stdin, " %99[^\n]", s);

the space at the beginning of the format consumes any initial whitespace in the input buffer, or clear the input buffer

int ch;
while((ch = getchar()) != EOF && ch != '\n);
if (ch == EOF) {
    // input stream broken?
    exit(EXIT_FAILURE);
}

before getting the input with either fgets or fscanf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM