我是一名C/C++开发人员,这里有几个问题总让我感到困惑.
谢谢
我在使用 fgets 时遇到问题。循环应该读取一行最大值。19 个字符,分析这个字符数组,然后等待下一个输入。问题是,如果输入的行超过 19 个字符,fgets 将用剩余的字符填充 str,直到输入 Ctrl-D 或换行符,从而在没有新输入的情况下启动新循环。输入 (stdin) 应该在读取 19 个字符后以某种方式刷新,因此循环可以从干净的石板开始。任何人都有解决方案?
char str[20];
while((fgets(str, 20, stdin) != NULL)) {
puts(str); //monitoring str
if(str[0] == 'q') break;
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
hola hola //user inputs 9 chars + newline
hola hola //puts writes
hoo hoo hoo hoo hooh //user inputs 20 chars + newline
hoo hoo hoo hoo hoo //puts writes
h //
Run Code Online (Sandbox Code Playgroud) 任何人都可以帮助我优化代码读取标准输入.这就是我现在拥有的:
unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
if (msgBytes >= (inputMsgBuffLen)) {
inputMsgBuffLen <<= 1;
if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
free(msg);
quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
}
}
msg[msgBytes] = (unsigned char)c;
}
Run Code Online (Sandbox Code Playgroud)