我想将文本文件中的内容复制到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;
}
a array
中的所有值都等于最后一行(点
答案 0 :(得分:4)
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
是一个字符串向量,每个都是文件中的一行
答案 1 :(得分:2)
您每次都会在inFile >> ab;
覆盖您唯一的缓冲区
你在缓冲区中读取一行并在某处保存缓冲区的地址。下次读取同一缓冲区中的下一行并保存与第二行完全相同的地址时。如果您回读第一行,您将最终读取更新的缓冲区,即最后一行。
您可以将代码更改为
#include <vector>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream inFile;
inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
string ab; //char ab[11];
int q=0;
vector< string > a(111); //char *a[111];
if (inFile.is_open()) {
while (!inFile.eof()) {
inFile >> ab;
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;
}
最好使用std :: string和std :: vector而不是数组。
答案 2 :(得分:2)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
bool ReadFile(const std::string &sFileName,
std::vector<std::string> &vLines)
{
std::ifstream ifs(sFileName);
if (!ifs)
return false;
std::string sLine;
while (std::getline(ifs, sLine))
vLines.push_back(sLine);
return !ifs.bad();
}
int main()
{
const std::string sFileName("Test.dat");
std::vector<std::string> vData;
if (ReadFile(sFileName, vData))
for (std::string &s : vData)
std::cout << s << std::endl;
return 0;
}
答案 3 :(得分:1)
为了阅读一行,你必须使用std::getline
。 >>
运算符只会读取单词,即以空格结尾的字符序列。
请参阅:http://en.cppreference.com/w/cpp/string/basic_string/getline