【发布时间】:2017-12-17 16:35:54
【问题描述】:
我想做一个程序,要求用户输入一个字符,然后输入...直到他想通过按 Enter 停止并且没有字符。
然后,程序会说:“你给了角色……”
例如:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
结果:你给了字符:kl
我的代码无法正常工作,因为当我按下回车键时,什么也没有发生。代码如下:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}
【问题讨论】:
-
首先在编译代码时阅读警告。将
%s替换为%c。在扫描while (str[i] != '\n')中的str[i]之前是什么?垃圾。先初始化还是别的什么 -
使用 fgetc 来一次读取一个字符。
-
数组未初始化,具有随机值
-
while (str[i] != '\n') 只是当用户按下回车键时停止程序的一种方式。这不是好方法吗?