/ *在文本文件中,我有一个char,后跟一个空格,然后是一个字符串。我正在尝试将char和string读取到单独的数组中。任何帮助表示赞赏* /
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char arrivOrDepart;
string licensePlt;
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
for (int i = 0; i < 4; i++)
{
getline(cin, arrivOrDepart[i]);
getline(cin, licensePlt[i]);
}
inFile.close();
cin.get();
return 0;
}
//文本文件 QWE123 ASD123 ZXC123 WER123 一个SDF123
答案 0 :(得分:1)
#include <fstream>
#include <iterator>
#include <vector>
这将从文件中读取到向量
std::ifstream input("d:\\testinput.txt");
std::vector<std::string> bytes(
(std::istreambuf_iterator<std::string>(input)),
(std::istreambuf_iterator<std::string>()));
input.close();
然后,将数据放入所需的任何容器中。你应该总是比数组btw更喜欢vector
答案 1 :(得分:1)
代码有一些问题:
getline
是错误的选择工具。如果要基于空格拆分流,请使用>>
。arrivOrDepart
和licensePlt
未定义为数组,而是用作数组。cin
读取,而不是从文件读取。我建议的解决方法(不包括使用向量代替数组):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std; // avoid using this
int main()
{
const int MAXARRAY = 4; // avoid using magic numbers
char arrivOrDepart[MAXARRAY]; // made an array, but prefer std::vector
string licensePlt[MAXARRAY]; //made an array
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
string temp;
int i = 0;
while (i < MAXARRAY && // not overrunning the arrays
inFile >> temp >> licensePlt[i] && // read data from file stream
temp.length() == 1) // read only one character for arrivOrDepart
{
arrivOrDepart = temp[0];
i++;
}
inFile.close();
cin.get();
return 0;
}
推荐阅读:
Why is "using namespace std" considered bad practice?
What is a magic number, and why is it bad?
std::vector
documentation(备用easier to read but often less accurate documentation)
std::getline
documentation.请注意用于设置解析定界符的第三个参数。