int main (){
char test1 [25];
printf("Enter a string:\n");
scanf("%s",&test1);
printf("%s\n",test1);
}
此代码应该只是打印并输入字符串。如果我进入" Hello Wolrd"它只打印"你好"结果是。我该如何解决这个问题?
答案 0 :(得分:2)
scanf
的 %s
仅读取空格或新行。而是使用fgets。
char buffer[256];
fgets(buffer, 256, stdin);
答案 1 :(得分:0)
scanf永远不会在输入中读取空格。
如果输入中有一个空格,它将被视为您正在读取的变量的输入结束。
使用fgets()
将您的输入转换为字符串,并sscanf()
进行评估。由于您只想要用户输入的内容,因此无论如何您都不需要sscanf()
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV[]) {
/* Allocate memory and check if okay. */
char *name = malloc (MAX_NAME_SZ);
if (name == NULL) {
printf ("No memory\n");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets (name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name)>0) && (name[strlen (name) - 1] == '\n'))
name[strlen (name) - 1] = '\0';
/* Say hello. */
printf("Hello %s. Nice to meet you.\n", name);
/* Free memory and exit. */
free (name);
return 0;
}
答案 2 :(得分:0)
不仅是scanf!
问题与%s转换有关。 它在文档中说:
%s Matches a sequence of non-white-space characters;
the next pointer must be a pointer to char, and the array
must be large enough to accept all the sequence and the
terminating NUL character. The input string stops at white
space or at the maximum field width, whichever occurs first.
您只能使用 fgets 来做您想做的事。
答案 3 :(得分:0)
%s
转换说明符表示scanf
从stdin
缓冲区中读取字符串。当遇到空白字符并且在scanf
返回之前将终止空字节添加到缓冲区时,读取停止。这意味着当你输入
"Hello Wolrd
^ space here
scanf
仅阅读Hello
并返回。 scanf
的相应参数应该是指向缓冲区的指针,即类型为char *
的指针,它存储字符串并且必须足够大以包含输入字符串,否则scanf
将超出缓冲区调用未定义的行为。但是&test1
具有类型char (*)[25]
,即指向25
个字符数组的指针。你需要的是
int main(void) {
char test1[25];
printf("Enter a string:\n");
scanf("%24[^\n]", test1);
printf("%s\n",test1);
return 0;
}
格式字符串%24[^\n]
中的 scanf
表示scanf
将读取长度最多为24的输入字符串,字符串不应包含换行符。如果任一条件失败,scanf
将返回。应为scanf
添加的终止空字节保存一个字符空间。因此,我们在格式字符串中使用24
而不是25
。
或者,您可以使用fgets
从流中读取一行。上面的scanf
调用可以替换为
char test1[25];
fgets(test1, sizeof test1, stdin);
fgets
最多从sizeof test1
读取少于stdin
个字符(为终止空字节保存一个字符空格)或直到它读取换行符 - 以先发生者为准。如果它读取换行符,则将其存储在缓冲区test1
中。
答案 4 :(得分:0)
在C中,字符串以'\0'
结尾。
在文本文件和控制台输入中,使用不同的标准。通常情况下,包括'\n'
在内的文字可能是一行或字符串。
scanf("%s", test1);
可以保存非空白文本。它会跳过前导空白区域,而不是扫描并保存非白色空间文本。它会一直持续到EOF条件或空白区域(例如' '
或'\n'
)。它不会节省空白。然后它会将'\0'
附加到目的地。
建议不要使用scanf()
,而是fgets()
,然后根据需要使用sscanf()
,strto*()
,strtok()
等解析收到的缓冲区。
fgets()
将保存所有文字。保存'\n'
或缓冲区已满后,它将停止。然后它会将'\0'
附加到目的地。它不会溢出目标缓冲区。
int main (){
char test1[25];
printf("Enter a string:\n");
fgets(test1, sizeof test1, stdin);
printf("%s",test1);
}