FStream - Reading Integers inside file C++ - c++

The objective is to read each integer in the following file and add them all up. But it seems I cannot cast the string line to an int for some reason.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string line;
ifstream file ("Random.txt");
int lines;
int amount = 0;
while(getline(file, line)){
lines++;
amount += static_cast<int>(line);
}
cout << amount;
return 0;
}
Txt file:
2
3
4
6
Any help would be much appreciated

No, you can't cast a string like that to anything, really.
If you know that the file contains only integers, you can just read them directly:
int number;
while (file >> number)
{
++lines;
amount += number;
}

A cast isn't the right tool to do so, it works for compatible types only.
What you actually need is a conversion function:
amount += std::stoi(line);
See the reference docs please.

Related

How to move filestream pointer to particular line without parsing each line (c++) [duplicate]

If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?
Loop your way there.
#include <fstream>
#include <limits>
std::fstream& GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for(int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return file;
}
Sets the seek pointer of file to the beginning of line num.
Testing a file with the following content:
1
2
3
4
5
6
7
8
9
10
Test program:
int main(){
using namespace std;
fstream file("bla.txt");
GotoLine(file, 8);
string line8;
file >> line8;
cout << line8;
cin.get();
return 0;
}
Output: 8
If every line has the same length then you can use istream::seekg() to jump to the location and read from there.
Here is a working and neat example with std::getline() if the lines have the same length:
#include <iostream>
#include <fstream>
#include <string>
const int LINE = 4;
int main() {
std::ifstream f("FILE.txt");
std::string s;
for (int i = 1; i <= LINE; i++)
std::getline(f, s);
std::cout << s;
return 0;
}
In general, no, you have to walk down using a strategy similar to what Xeo shows.
If as netrom says you know the lines have fixed length, yes.
And even if the line lengths are not known in advance, but (1) you're going to want to jump around a lot and (2) you can guaranteed that no one is messing with your file in the mean time you could make one pass to form a index, and use that thereafter.
you can use while loop as well
fstream f;
f.open("bla.txt", ios_base::in);
int i = 1;
int line = 8;
while(i != line){
f.ignore(1000, '\n');
++i;
}
string fContent;
f >> fContent;
cout << fContent;
Note: create the file first

Reading string then int line by line in C++

So, I have a file that contains a pattern of a string then an int alternating line by line.
Something like this:
John McClane
30
James Bond
150
Indiana Jones
50
In this example, I would set John McClane to a string variable and then 30 to an integer variable. My issue is dealing with two types. I want to use getline(), but that only works with strings.
Is there an efficient or "right" way of doing this?
There are a number of approaches you could try.
Get string input, and convert to an integer if valid
Convert every second string to an integer
Try to read an integer when you expect one (just using cin >> in;). If you want a robust program, you can check validity with cin.good()
I don't know if there is a "right" way of doing this per say, but it's not a very taxing operation, so whatever you choose should be fine.
You could make a variable like this
string ibuf;
Then convert it to an integer doing this
getline(cin, ibuf);
(Whatever your int variable is) = strtol(ibuf.c_str(), NULL, 10);
One thing about C++ is that there are a large number of ways to accomplish any one task. One way to get integers from strings is to use a stringstream. There is a tutorial on stringstreams here
As for your problem with reading the alternating file, consider the following pseudocode:
boolean isInt = false;
while(fileIsNotOver) {
//getline
if(isInt) {
//use stringstream to get int here
} else {
//do whatever with the name here
}
isInt = !isInt;
}
I don't know if this fully works as i didn't tested it however it just compiles fine and answer should be something like this i think.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int counter = 0;
int number;
string test_string;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,test_string) )
{
cout << test_string << '\n';
++counter;
if(counter % 2 == 0 ){
number = atoi(test_string.c_str());
cout << number << '\n';
}else{
cout << test_string << '\n';
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
You can try like this to read a string then an int alternating line by line.
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
string name;
int number;
freopen("input.txt", "r", stdin);
while (getline(cin, name))
{
cin >> number;
/*
process the input here
...
...
*/
getline(cin, name); // just to read the new line and/or spaces after the integer
//getchar(); //you can use getchar() instead of getline(cin, name) if there is no spaces after the integer
}
return 0;
}
Thanks !!!

how to read data delimited by space and save it to arrays,and then write it other order in new text file in c++

psedo code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
double beta[250];
char Batob[250], eq[250];
ifstream myfile("iter1/HMMemit0.txt");
if (myfile.is_open())
{
int i = 0;
while (getline(myfile, line))
{
istringstream iss(line);
if (!(iss >> Batob[i] >> eq[i] >> beta[i])){ //it store only B in Batob[i], but i want to save B00 in Batob[i], = in eq[i], and 0.524671 in beta[250]
break;
}
i++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
my data stored in HMMemint0 like this
B00 = 0.524671
B01 = 0.001000
B02 = 0.001000
B10 = 0.001097
B11 = 0.001000
B12 = 0.001000
i want to read a line and save each term in each variable like B00 saved in name[i], and 0.001000 in beta[i].
and then, write it in this 0.524671(B00's value) 0.001097(B10's value) order like this
0.524671 0.001097
0.001000 0.001000
0.001000 0.001000
How can i do it? please help me.
You are having a char array for "BXX"s, whereas you want strings. Basically, you want a string array, or even vector. The problem is that only 'B' will be read from "BXX" into your first parameter.
This code works for me:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
double beta[250];
string Batob[250];
char eq[250];
ifstream myfile("iter1/HMMemit0.txt");
if (myfile.is_open())
{
int i = 0;
while (getline(myfile, line))
{
istringstream iss(line);
iss >> Batob[i] >> eq[i] >> beta[i];
i++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Disclaimer: I was just fixing your code with the least impact, but of course if you start using proper C++ containers like vector, the i variable could be easily eliminated as the elements and the index would be maintained automatically.
Also, since you are using the equal sign ('=') all the time for the char array, it is a bit needless waste of memory, which could be severe in case of a big file.
I would say, using an associate container in the future would be even more productive for your BXX keys and their corresponding values on the right side.
Batob is an array of characters, so Batob[i] is a single character. That's why your program reads only one character. If you want to read 250 strings of characters you need to make room for them. The simplest (not necessarily the best, however) method is to declare an array like char Batob[250][100] – this would be an array of 250 arrays, 100 characters each. Then Batob[i] is a 100-chars array and you can input a string with iss >> Batob[i].

How to read a file line by line or a whole text file at once?

I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error

In C++ is there a way to go to a specific line in a text file?

If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?
Loop your way there.
#include <fstream>
#include <limits>
std::fstream& GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for(int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return file;
}
Sets the seek pointer of file to the beginning of line num.
Testing a file with the following content:
1
2
3
4
5
6
7
8
9
10
Test program:
int main(){
using namespace std;
fstream file("bla.txt");
GotoLine(file, 8);
string line8;
file >> line8;
cout << line8;
cin.get();
return 0;
}
Output: 8
If every line has the same length then you can use istream::seekg() to jump to the location and read from there.
Here is a working and neat example with std::getline() if the lines have the same length:
#include <iostream>
#include <fstream>
#include <string>
const int LINE = 4;
int main() {
std::ifstream f("FILE.txt");
std::string s;
for (int i = 1; i <= LINE; i++)
std::getline(f, s);
std::cout << s;
return 0;
}
In general, no, you have to walk down using a strategy similar to what Xeo shows.
If as netrom says you know the lines have fixed length, yes.
And even if the line lengths are not known in advance, but (1) you're going to want to jump around a lot and (2) you can guaranteed that no one is messing with your file in the mean time you could make one pass to form a index, and use that thereafter.
you can use while loop as well
fstream f;
f.open("bla.txt", ios_base::in);
int i = 1;
int line = 8;
while(i != line){
f.ignore(1000, '\n');
++i;
}
string fContent;
f >> fContent;
cout << fContent;
Note: create the file first