【发布时间】:2014-06-11 02:26:22
【问题描述】:
我想将文本文件中的内容复制到string 或*char。如果我可以将文件内容复制到字符串的array 会更好(每一行都是那个array 的元素)。这是我的代码:
int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
char ab[11];
int q=0;
char *a[111];
if (inFile.is_open()) {
while (!inFile.eof()) {
inFile >> ab; //i think i don't understand this line correctly
a[q]=ab;
cout<<a[q]<<endl;
q++;
}
}
else{
cout<<"couldnt read file";
}
inFile.close();
cout<<"\n"<<ab<<endl; //it shoud be "." and it is
cout<<"\n"<<a[0]<<endl; //it should be "ion" but it gives me "."
return 0;
}
array 中的所有值都等于最后一行,即点
【问题讨论】:
-
检查this
-
您应该使用
std::vector<std::string>而不是字符指针数组。另外,您希望每一行都在自己的字符串中,还是每个单词中? -
每一行只有一个单词,所以对我来说没什么区别
-
@MohitJain 谢谢我会检查的
-
不要这样做
while (!inFile.eof()),它不会像你期望的那样工作,并且会导致你迭代一次到多次。而是做while (inFile >> ab)。原因是eofbit标志直到在您尝试从文件末尾读取之后才设置。
标签: c++ arrays fstream ifstream