【发布时间】:2021-12-19 00:33:45
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
void main (int argc, char* arcv[]) {
int fd, quest_num, i, j;
char* str;
char temp[2], buffer[20];
fd = open(arcv[1], O_WRONLY | O_CREAT, 0664);
printf("Insert number of questions\n");
scanf("%s", str);
write(fd, str, sizeof(str));
write(fd, "\n", 1);
quest_num = atoi(str);
for (i = 1; i <= quest_num; i++) {
printf("Insert question %d\n", i);
scanf("%[^\n]s", buffer);
printf("\n %s \n", buffer);
write(fd, "Question ", );
sprintf(temp, "%d", i);
write(fd, temp, sizeof(temp));
write(fd, "\n", 1);
write(fd, str, sizeof(temp));
write(fd, "\n", 1);
}
close(fd);
}
我想这样输入:
Insert Number of Question:
2
Insert Question 1:
X+1=0 x=?
Insert Question 2:
X+y=0
在文件内容中我希望它看起来像这样:
Question 1: X+1=0 x=?
1. 5
2. 2
3. 0
4. 1 Question 2: X+y=0
1. X=y
2. X= y
3. X=1
4. Y=1
但我在终端得到了这个:
Insert number of questions
2
Insert question 1
x+y x=?
Insert question 2 (input is ignored here)
在文件里面:
2
Question 1
x+
Question 2
x=
Question 3
2
总而言之,scanf 忽略了空格输入,文件内容中有一个额外的循环。
【问题讨论】:
-
为什么
%[^\n]后面有s?那永远不会匹配任何东西。 -
@Barmar 我试过 %[^\n]s、%[^\n] 和 %s。它们都不起作用
-
您从未为
str分配任何内存,因此您会导致scanf("%s", str);出现未定义的行为。 -
sizeof(str)是指针的大小,而不是输入的字符数。使用strlen()获取字符串的长度。 -
使用
scanf("%s")后,输入缓冲区留在换行符处。下一个scanf("%[^\n]s", buffer);将立即停止,因为没有非换行符。