我有这个txt文件
我如何将这个文件从''读到''写到ArrayList?
我想你指的是java的 ArrayList
它在C++中的等价物是 std::vector
. 另外,我假设你想将分号之间的每个字符串存储在 ArrayList
. 我还假设该文件名为 input.txt
.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
int main()
{
std::vector<std::string> strings;
std::ifstream input("input.txt");
std::string tempString;
while (std::getline(input, tempString, ';'))
strings.push_back(tempString);
for (auto& str : strings)
std::cout << str << '\n';
}
输出。
ENG222
COMPUTER PROGRAMMING II
2
6
C
D
DR. JIM
ENG111
COMPUTER PROGRAMMING I
1
4
C
D
DR. JOHNSON
ENG313
MATH I
3
3
E
D
DR. ALISSON
ENG104
CHEM
1
5
C
D
DR. SAM
编辑:
我从评论中了解到,你想把每一列都添加到一个... ArrayList
. 我假设列数只是......。7
. 如果你想让列数变化,你可以通过某种方式输入数值,也许可以从文件中读取数值 (input >> columns
)或从标准输入中读取 (std::cin >> columns
). 在这段代码中,如果某行只包含4个值,例如,我认为其余的3个值是空的。
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
int main()
{
std::ifstream input("input.txt");
int columns = 7;
/*
// in case the columns count is not constant.
// to read from the file. in this case, the number should be at the begining of the file.
input >> columns;
// to read from the standard input (from the terminal).
std::cin >> columns;
// to white spaces.
input.ignore();
*/
std::vector<std::vector<std::string>> values(columns);
std::string tempLineString;
std::string tempWordString;
while (!input.eof())
{
std::getline(input, tempLineString);
std::istringstream iss(tempLineString);
int i = 0;
while (i < columns && std::getline(iss, tempWordString, ';'))
{
values[i].push_back(tempWordString);
i++;
}
while (i < columns)
values[i++].push_back("");
}
for (int i = 0; i < columns; i++)
{
std::cout << "Column " << i + 1 << " values: \n";
for (auto& str : values[i])
std::cout << str << '\n';
std::cout << '\n';
}
}
輸出結果。
Column 1 values:
ENG222
ENG111
ENG313
ENG104
Column 2 values:
COMPUTER PROGRAMMING II
COMPUTER PROGRAMMING I
MATH I
CHEM
Column 3 values:
2
1
3
1
Column 4 values:
6
4
3
5
Column 5 values:
C
C
E
C
Column 6 values:
D
D
D
D
Column 7 values:
DR. JIM
DR. JOHNSON
DR. ALISSON
DR. SAM