简体   繁体   English

scanf(“%s”,s);会发生什么? 遇到两个或两个以上的单词,并且只提供了一个变量?

[英]What happens when a scanf(“%s”,s); encounters two or more words and only one variable is provided?

When a scanf("%s",s); scanf("%s",s); (one of many ways to get a string which is not perfect) encounters a space in the input, it will try to put it in another variable, right? (获取不完美字符串的多种方法之一)在输入中遇到空格,它将尝试将其放入另一个变量中,对吧? But what hapens if there is only one variable provided as in this case? 但是,在这种情况下,如果仅提供一个变量,会发生什么情况?

Also what other ways are used to input a string? 还有什么其他方式可以用来输入字符串? which is the esiest or best one to use and which one does not give problems like the gets(s); 哪一种是最容易使用或最好的,并且不会像gets(s);这样的问题gets(s); function? 功能?

Here is my s_insert function now: 现在是我的s_insert函数:

// pointer to pointer needed when you allocate memory in the function
void s_insert(char **string_one){   //inserts string (loss of original data)
    *string_one=(char*)malloc(200);
    fgets (*string_one,200,stdin);
} 

scanf for %s data specification reads characters before first space symbol (' ', '\\n' or '\\t'). scanf for %s数据规范读取第一个空格符号(“,” \\ n”或“ \\ t”)之前的字符。 If you want to read string with spaces (more than two words) use fgets function, that is more safe than 'gets' because you can set the maximum number of character that can be allocated in your memory and avoid segmentation fault. 如果要使用空格(两个以上的单词)读取字符串,请使用fgets函数,这比“ gets”更为安全,因为您可以设置可以在内存中分配的最大字符数,并避免出现分段错误。

No, it will only try to "put in a variable" when it encounters a % with a suitable conversion specifier in the first argument. 不,它只会在遇到第一个参数中带有合适的转换说明符的%时尝试“放入变量”。 That argument is what controls its behavior, not the input. 该参数控制其行为,而不是输入。

Having a single %s and multiple words in the input will simply leave the remaining words still in the input buffer, since scanf() will stop when it's done with the single %s , it has nothing more to do then. 在输入中只有一个%s和多个单词会简单地将其余单词留在输入缓冲区中,因为用单个%s完成scanf()会停止,因此它无事可做。

It reads its conversion specification string and tries to read input to match that, not the other way around. 它读取其转换规范字符串,并尝试读取输入以匹配该字符串,而不是相反。

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

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