简体   繁体   English

字符串仅录制第一个单词

[英]String Only recording first word

I am just getting started with programming in C and am writing a cypher/decypher program. 我刚刚开始使用C语言进行编程,我正在编写一个cypher / decypher程序。 The user is asked to type in a phrase which is stored as a char *. 要求用户输入存储为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. 使用fscanf不会等待用户输入。 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. 它只是打印“请输入短语...”然后退出fgets也做同样的事情,程序不等待输入,只打印“PLease enter ...”然后退出。

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 . 在使用fgetsfscanf获取输入之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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