【发布时间】:2014-11-10 08:12:36
【问题描述】:
考虑一个简单的程序。它必须从标准输入获取字符串并保存到变量。 没有说明会输入多少行,但如果遇到换行符,程序必须终止。
例如: 标准输入:
abc
abs
aksn
sjja
\n
我试过了,但它不起作用。这是我的代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
// Constant
#define max 100000
struct chuoi
{
char word[10];
};
chuoi a[max];
void readStr()
{
int i=0;
while ( fgets(a[i].word, 10,stdin) != NULL)
{
if (a[i].word[0] == ' ') break;
a[i].word[strlen(a[i].word)-1] = '\0'; //replaced \n by \0
i++;
}
//length = i;
}
int main()
{
readStr();
return 0;
}
那么,如何解决这个问题呢?
【问题讨论】:
-
“我试过了”——嗯?
a[i].word[0] == ' '- 没有任何意义。 -
只是“它不起作用”。永远不能作为问题陈述被接受。以什么方式不起作用?您究竟在哪里遇到了问题,您尝试了哪些方法?
-
对于 C++,您应该使用
std::string和std::vector。另外,don't use fgets(为什么不是 C++ IO?) -
为什么包含 iostream 却没有任何用处?这几乎是您正在编写的 C,而不是 C++。