I have a data.txt file, and its contents are:
[exe1]
1 0 2 9 3 8
----------
[exe2]
----------
10 2 9 3 8:0
I want to read line 2: 1 0 2 9 3 8. But my output is only 1.
My code:
#include <iostream>
#include <fstream>
#include <limits>
#include<string>
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;
}
int main() {
using namespace std;
fstream file("data.txt");
GotoLine(file, 2);
std::string line2;
file >> line2;
std::cout << line2;
cin.get();
return 0;
}
What is my problem? Sorry, I'm new in programming.
file >> line2; will stop reading a the first white space and hence reads only "1" because the extraction operator >> uses space as a deliminator.
you may want to use getline as getline(file,line2)
The input operator >> reads space delimited strings, if you want to read a whole line you need to use std::getline:
std::string line2;
std::getline(file, line);
Related
Let's say I have a txt file
Rahim
5 6 7
Karim
6 7 8
Rahman
7 8 9
I want to save those name in a vector and I want to put those number in a nested vector as integers.
I tried this but it's not working.
#include <string>
#include <vector>
using namespace std;
int main(){
vector<vector<int> > data;
vector<int> temp;
vector<string> nameF;
string file;
cout << "Enter a file: ";
cin >> file;
ifstream infile(file);
if(!infile.good()){
cout << "Enter a valid file: " << endl;
return 1;
}
string name;
string values;
while(!infile.eof()){
getline(infile, name);
getline(infile, values);
if(!infile.fail()){
nameF.push_back(name);
for(int i = 0; i < values.length(); i++){
string s = values.substr(i, values.find(" "));
temp.push_back(stoi(s));
}
data.push_back(temp);
}
}
}
So I suggest you use an istringstream to read the integers from the second string
#include <sstream>
nameF.push_back(name);
istringstream buffer(values);
vector<int> temp;
int value;
while (buffer >> value) {
temp.push_back(value);
}
data.push_back(temp);
An istringstream lets you read from a string as if it was any other input source. So it's an easy way to convert a whitespace separated string of integers.
Another problem in your original code is that you reuse temp for each line without clearing it in between. So each line is going to add to the integers that are already there from previous lines. I've fixed that problem by moving the declaration of temp to inside the loop, but you could just call temp.clear(); before the integer reading loop.
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string str;
getline(cin,str);
stringstream ss(str);
vector<int> arr;
while(!ss.eof()){
int num;
char ch;
ss>>num>>ch;
arr.push_back(num);
}
for(int i=0;i<arr.size();i++){
cout<<arr.at(i)<<endl;
}
return 0;
}
I am getting output for 1,2,3,4,5 as
1
2
3
4
5
but for 1 2 3 4 5 it is
1
3
5
why? space is also a character so it should work or am I missing something?
thank you for helping.
Because formatted input operations skip whitespaces. Thus the following happens:
ss >> num // reads integer 1
>> ch; // skips whitespace after 1 and reads char '2'
In the next iteration:
ss >> num // skips whitespace after 2 and reads integer 3
>> ch; // skips whitespace after 3 and reads char '4'
And the last iteration:
ss >> num // skips whitespace after 4 and reads integer 5
>> ch; // Encounters eof, nothing is read
Don't read that char for space-seperated lists. Or You can use std::noskipws to change this behaviour.
Extraction operator “>>” provides reading space separated integers without reading a separator by:
ss >> num;
instead of additional reading of separator in original code:
ss >> num >> ch;
because for standard streams, the skipws flag is set on initialization.
And this makes more simple reading space separated integers.
To make both separators working similar add
ss >> noskipws;
as in following code:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main () {
string str;
getline (cin, str);
stringstream ss (str);
ss >> noskipws;
vector<int> arr;
while (!ss.eof ()) {
int num;
char ch;
ss >> num >> ch;
arr.push_back (num);
}
for (int i = 0; i < arr.size (); i++) {
cout << arr.at (i) << endl;
}
return 0;
}
I am new to programming and I have a data.txt file with the following content:
bumbumbow
1 0 3 9 8
bumbumbum
1 0 3 9 :0
I want to read the line 2: 1 0 3 9 8 and to turn it into integer numbers but I have an error.
What is the problem? Here is my code:
#include <iostream>
#include <fstream>
#include <limits>
#include<string>
#include<vector>
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;
}
int main() {
int result, i = 0;
std::vector<int> Array;
using namespace std;
std::fstream file("data.txt");
GotoLine(file, 2);
std::string line2;
std::getline(file, line2);
for (int result; std::getline(file, line2); result = std::stoi(line2))
{
Array.push_back(result);
std::cout << "Read in the number: " << result << "\n\n";
}
return 0;
}
thanks in advance guys
The crash occures due to calling std::stoi() with a wrong parameter "1 0 3 9 8".
You need to replace std::getline(file, line2); result = std::stoi(line2) inside the for loop with something splitting line2 into tokens and calling std::stoi() for those tokens. You can see how to split, for example, here:
Right way to split an std::string into a vector<string>
I am having trouble displaying the contents of a vector. I am unsure whether it is the way I read in the values from the text file, or whether my display function is just not working.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n,length;
std::vector<int>arr1;
fstream file("t1.txt");
if(file.is_open())
{
while (getline(file,line))
{
cout << line << endl;
}
file << line;
length = line.length();
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
}
return 0;
}
Any help would be greatly appreciated.
the text file contains "5 2 5 5 -1 7 2 5 3 5 2 -2"
I suppose you have a problem with vector building (reading values from file to vector). You should delete (or comment) expression with getline, as well as writing line back to file (file << line), and use only file >> n.
Try the following shortened version of your program
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n;
std::vector<int> arr1;
fstream file("t1.txt");
if(file.is_open())
{
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
file.close();
}
return 0;
}
Problem of your initial code is that after you read line from your file (that comprises only one line) next reading (whether it is file >> ... or getline(...)) will provide no data because END OF FILE. To read data from file again you should re-open it
...
length = line.length();
file.close();
file.open("t1.txt");
while(file >> n)
arr1.push_back(n);
...
or rewind to the beginning
...
length = line.length();
file.clear();
file.seekg(0, ios_base::beg);
while(file >> n)
arr1.push_back(n);
...
But you should understand, that writing to file stream does not provide desired effect - the recorded data will be available only after transfer written data from the buffer to the file (in the general case, after the file closing).
EDIT:
Also I want to add, that C++ allows input to and output from vector without additional loops, just consider the following example
if(file.is_open())
{
// filling vector from the stream
istream_iterator<int> it(file); // iterator for int values in file
istream_iterator<int> eos; // end of straem
arr1.insert(arr1.begin(), it, eos);
// output vector to the stream (cout = standard output stream)
ostream_iterator<int> oit (cout,"\n"); // "\n" = new line is a separator for output
// also " " or any other separator can be used
copy(arr1.begin(), arr1.end(), oit);
}
Am reading a file which contains list of sentences , I need to read each word and try to figure out this word in which line number ..
the file contains :
I am for truth
no matter who tells it,
I am for justice,
no matter who it is for or against
Malcom X
and I want the output to be in this form :
against 4
matter 4
am 1, 3
no 2, 4
for 1, 3, 4
or 4
I 1, 3
tells 2
is 4
truth 1
it 2, 4
who 2,4
justice 3
X 5
Malcolm 5
am using binary search trees and here is my code :
int main(int argc, char *argv[]) {
fstream infile ;
BSTFCI <string>* bst = new BSTFCI<string>();
string word;
string line;
infile.open("test.txt" , ios::in);
if(infile.fail())
{
cout<<"Error Opening file"<<endl;
return 0;
}
while(!infile.eof())
{
infile>>word;
for(int i=0 ; i<word.size();i++)
{
if(ispunct(word[i]))
word.erase(i,1);
}
cout<<count<<endl;
if(!bst->search(word))
{
cout<<word<<endl;
bst->insert(word);
cout<<"add"<<endl;
}
else
{
cout<<word<<endl;
cout<<"exist"<<endl;
}
}
infile.close();
return 0;
}
This might get you started,
#include <string>
#include <fstream>
#include <sstream>
// read the file line by line
int line_number = 0;
string line;
while (getline(infile, line))
{
++line_number;
// put the line in an istringstream
istringstream buffer(line);
// read the words from the line
string word;
while (buffer >> word)
{
// do something with word and line_number
// save them in some data structure
}
}