我正在尝试进行简单的字符串获取。我需要的是从输入 (stdin) 中写入一个字符串,它可以包含空格,并保存它 没有 单词之间的任何空格。
到目前为止,我已经编写了这个保存所有内容(包括空格)的简单代码,但我不知道如何让 scanf()
忽略空格。
int main(){
char str[10];
scanf("%[^\n]s, str);
printf("%s", str;
}
例如:
如果我的输入是:I love C programming!
我的输出应该是:IloveCprogramming!
我尝试使用%*
,用于忽略字符,但没有成功。
我也知道我可以在保存后“重新扫描”字符串并删除所有空格,但我需要尽可能高效地进行此获取,并且重新扫描每个字符串以删除空格会大大增加计算时间(而不是简单的扫描和忽略,其复杂度为 O(n))
最佳答案
您为这项工作使用了错误的工具。您需要使用 getc
然后执行以下操作
int ch;
char str[10];
// Loop until either loop reaches 9 (need one for null character) or EOF is reached
for (int loop = 0; loop < 9 && (ch = getc(stdin)) != EOF; ) {
if (ch != ' ' ) {
str[loop] = ch;
++loop;
}
}
str[loop] = 0;
printf("%s", str);
无需重新扫描
关于C - 忽略 scanf() 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51556986/