How to read in individual characters from txt.file in C++? - c++

I have a txt file that contains individual characters line by line. I am kind of confused as to how to read that line by line when the getline function takes in string?
Also would it be possible to store char in a vector? Or would it still work if I stored those individual characters as strings?

code show as below:
vector<char> res;
int count = 0;
ifstream fin;
fin.open("***.txt");
string str;
while (!fin.eof())
{
getline(fin, str);
res[count++] = str;
}
fin.close();

Related

How to create an array by reading a file in c++ if every line contains an integer?

In C++ I should read a file in which every line contains an integer and transfer every integer into an array. I tried doing count the lines with getline() function. And created array however when I count the lines, it consumes and if I use getline() function again, it won't work. What should I do? Thank you.
ifstream inFile( fileName );
if ( inFile.is_open() ) {
int size = 0;
string line;
while( getline(inFile, line))
size++;
int* array = new int [ size ];
while ( getline( inFile, line )) {
....
}
}
The code does not enter the second while.
Reset fstream before second while loop
inFile.clear();
inFile.seekg(0, std::ios::beg);
while ( getline( inFile, line )) {
....
When this loop completes:
while( getline(inFile, line))
// ...
the stream inFile has been exhausted, and there's no more data to read from it.
One option is to open the file again, and then read from it. However, this is wasteful, since you can keep track of the numbers you read from the file the first time:
std::vector<int> v;
int i;
while (inFile >> i)
v.push_back(i);
Now you have all the numbers in a container, and you don't need to read from the file again.
Note that I'm using std::vector instead of an array, since it's much easier to work with.
If you absolutely must use an array, then you can read the file once to figure out how many integers are in the file:
int i, count = 0;
while (inFile >> i);
and then allocate memory for an array:
int *array = new int[count];
and then open the file again, and read into the array:
int i = 0;
while (inFile >> array[i++]);
you can read the file into a string and then work with the string instead of with the file
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string stringOfNumbers = buffer.str();
and from there split the string by the newline characters parse the split strings as ints

Read File and store in a array of chars - c++

I'm trying to open a file and save the information there in an array of chars, however I'm not getting it. To save in a string use this:
int main(){
string line1;
ifstream myfile;
myfile.open("example.txt");
if(!myfile){
cout<<"Unable to open the file."<<endl;
exit(0);
}
while(getline(myfile,line1)){
ReadFile(myfile);
}
}
And It works.
When I use an array of chars, I code like this:
int main(){
int size=100;
char line1[size];
ifstream myfile;
myfile.open("example.txt");
if(!myfile){
cout<<"Unable to open the file."<<endl;
exit(0);
}
while(myfile.peek()!EOF){
line1[size]->ReadFile();
}
}
The function ReadFile is this:
void ReadFile(ifstream &is){
char aux[100];
is.getline(aux,100);
}
To read in an array of characters, or text, you can use std::getline and std::string:
std::string text;
std::getline(myfile, text);
To process text lines in a file:
std::string text;
while (std::getline(myfile, text))
{
Process_Text(text);
}
Don't use arrays of characters, as they can overflow. Also, instead of using == to compare, you'll have to use strcmp. Always verify that your array of characters is terminated by a nul character, '\0', otherwise the string functions will go beyond your array, not stopping until a nul is found.
Edit 1: Space separated
To read in text that is space separated, use:
std::string text;
myfile >> text;
Edit 2: Counting characters in a string
You can count characters in a string by using another array.
unsigned int frequency[128] = {0}; // Let's assume ASCII, one slot for each character.
// ... read in string
const size_t length(text.length());
for (size_t index = 0; index < length; ++index)
{
const char letter = text[index];
++frequency[letter];
}

How to get a specific line from a .txt (C++)

I would like some help with getting the first line from a txt file called "test.txt", I have discovered the getline function however I am not sure why my code doesn't work or what I need to do. I would like to get the first line from the .txt file, but it prints "t" for some reason. Feel free to correct me as you please if I am not handling it correctly. This is the code I am using:
string FirstLine;
ifstream File("test.txt");
string line;
if (File)
{
while (getline(File, line))
{
FirstLine = line[0];
}
File.close();
}
cout << FirstLine;
And this is the .txt file:
this is line 1
this is line 2
this is line 3
If you just want the first line:
string line;
getline(File, line);
Your first line of the file is then stored in line as a, you guessed it, string
To get all lines (line by line):
while(getline(File, line).good())
//do something with line
string FirstLine;
ifstream File("test.txt");
string line;
if (File)
{
getline(File, line);
FirstLine = line;
File.close();
}
cout << FirstLine;
Is the absolute minimum changes you need to your code to make it do what you want to do. However, there is A LOT of room for improvement on the above code sample. For example, why create two strings, line, and FirstLine, just pass FirstLine to the getline() function. I just modified what you provided to highlight where the mistakes where. Hope this helps...

Error using getline with ifstream - C++

I need help, I tried googling if I could find a similar problem but the solutions for others didn't work for me.
I'm trying to use getline() to read the file I've opened but it's not accepting the parameters I've given it.
What I'm trying to accomplish at this time (not the entire program) is to open a .csv file and determine how many elements it has inside by using getline() and using the , character as the delimiter. My loop has an index which I could just add 1 to it so that I can get the total number of elements inside the file.
The reason I'm doing this is because I intend to use it for a project at school but so far I've gotten stuck at the getline() error:
no matching function for call to 'std::basic_ifstream::getline(std::string&, int, const char [2])'
My code is here:
void readfile(string a)
{
int i = 0;
ifstream infile;
infile.open(a.c_str());
string temp;
//count how many elements are inside
if(infile.is_open())
{
while(infile.good())
{
infile.getline(temp, 256, ",");
i++;
}
infile.close();
i+=1;
}
else
{
cout<<"Error opening file.";
}
cout<<i;
}
Use the free getline() function:
std::string line;
getline(infile, line);
In addition to the answer by #UlrichEckhardt, I'd handle delimiters like this:
if(infile.is_open())
{
string temp;
// std::getline(std;:istream&, std::string) used below
while(getline(infile, temp)) {
std::stringstream stream(str);
std::string token;
while (std::getline(stream, token, ','))
if (!token.empty()) // it's up to you to decide how to handle empty tokens
i++;
}
}
Note the ','. If it were ".", this would be considered a string by the compiler, which is exactly what you're seeing in the error message: a '\0' is appended automatically, thus producing a char[2].

Creating String Array from CSV

I have a csv file of atomic elements with atomic number, symbol, and name. The file is formatted as:
1,H,Hydrogen
2,He,Helium
3,Li,Lithium
...
I'd like to create an array of the symbols referenced by the atomic number. ie. ArrayName[32]="Ge";
I've been trying to use sscanf but it hasn't been working. rough code below:
char temp[200];
float temp_z;
std::string temp_ele;
std::string temp_name;
while(!fin.eof())
{
fin.getline(temp,200);
sscanf(temp, "\"%f\",\"%s\", \"%s\"",&temp_z, &temp_ele, &temp_name);
cout<<temp_z<<endl;
cout<<temp_ele<<endl;
cout<<temp_name<<endl;
}
Read every line of your file with this loop :
string line;
ifstream myfile;
myfile.open("myfile.txt");
if(!myfile.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
while(getline(myfile, line)) {
// Split line by comma to get what's your want
}
Then split every line by comma to get every element of the line.
You can read each element like so:
string theStrings[200]; //initialize to correct size
int i = 0;
string name;
while(!fin.eof())
{
getline(thefilestream, name, ',' );
theStrings[i++] = name;
cout<<name<<endl;
}