简体   繁体   English

scanf循环直到回车

[英]scanf in a loop till carriage return

I am trying to read user input with multiple fields. 我试图读取多个字段的用户输入。 But the number of fields is not specified. 但是没有指定字段数。 I want to read all the words till the carriage return. 我想读回所有的字,直到回车。 i tried this code but it isnt working: 我试过这段代码,但它不起作用:

char str[256];
while(1)
{
    scanf("%s", str);
    if(str[strlen(str)] == '\n')
         break;
    else
         printf("Got %s\n", str);

}

Examples of user input: 用户输入示例:
1. store file1 1.存储文件1
I need to parse store and file1 and break out of the loop. 我需要解析store和file1并打破循环。
2. store file1 file2 2.存储file1 file2
I need to parse store, file1 and file2 and break out of the loop. 我需要解析store,file1和file2并打破循环。

Wondering how to break out of the loop at the carriage return. 想知道如何在回车时突破循环。

thanks. 谢谢。

Use 采用

char str[256]
scanf("%255[^\n]", str); /*edit*/

which will read to a newline or (Edit:) 255 characters, whichever comes first. 它将读取换行符或(编辑:) 255个字符,以先到者为准。

You could read using fgets() then split the buffer using strtok() into tokens 您可以使用fgets()读取,然后使用strtok()将缓冲区拆分为标记

that way you have full control of everything. 这样你可以完全控制一切。

目前,你的char数组str [256]没有任何东西或垃圾,所以当你查找时,你将找不到它。

Try this. 尝试这个。

char str[256];
while(1)
{
    scanf("%s", str);
    printf("Got %s\n",str);
    if(fgetc(stdin) == '\n')
        break;
}
char str[256]
scanf("%256[^\n]", str);

Be careful with that code. 小心那些代码。 It will overflow the char array for long strings. 它将溢出char数组以获得长字符串。 You want %255 in the scanf to accommodate the null terminator. 您希望scanf中的%255容纳空终止符。

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

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