I have this txt file
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
how can i read and write this file to ArrayList from ';' to ';' in C++
I suppose that you mean java's ArrayList
which has an equivalence in C++ of std::vector
. Also I assume that you want to store each string between the semicolons inside the ArrayList
. I also assume that the file is called 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';
}
Output:
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
Edit:
I've understood from the comments that you want to add each column to an ArrayList
. I'll assume that the number of columns is just 7
. If you want the number of columns to vary, you can input the value somehow. maybe by reading the value from the file ( input >> columns
) or by reading it from the standard input ( std::cin >> columns
). In this code, if some row contains only 4 values for example, I consider the rest of the 3 values to be empty.
#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';
}
}
Output:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.