我想将文本文件中的内容复制到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
中的所有值都等于最后一行是点
最佳答案
int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
std::vector< std::string > lines;
std::string line;
if (inFile.is_open()) {
while ( getline( inFile, line ) ) {
lines.push_back( line );
}
}
...
现在 lines
是一个字符串 vector ,每个都是来自文件的一行
关于c++ - 将文件内容复制到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291995/