I am trying to read all integers from a file and put them into an array. I have an input file that contains integers in the following format:
3 74
74 1
1 74
8 76
Basically, each line contains a number, a space, then another number.
I know in Java I can use the Scanner method nextInt() to ignore the spacing, but I have found no such function in C++.
#include <fstream>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> arr;
std::ifstream f("file.txt");
int i;
while (f >> i)
arr.push_back(i);
}
Or, using standard algorithms:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> arr;
std::ifstream f("file.txt");
std::copy(
std::istream_iterator<int>(f)
, std::istream_iterator<int>()
, std::back_inserter(arr)
);
}
int value;
while (std::cin >> value)
std::cout << value << '\n';
In general, stream extractors skip whitespace and then translate the text that follows.
// reading a text file the most simple and straight forward way
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int main () {
int a[100],i=0,x;
ifstream myfile ("example.txt");
if (myfile.is_open()) // if the file is found and can be opened
{
while ( !myfile.eof() ) //read if it is NOT the end of the file
{
myfile>>a[i++];// read the numbers from the text file...... it will automatically take care of the spaces :-)
}
myfile.close(); // close the stream
}
else cout << "Unable to open file"; // if the file can't be opened
// display the contents
int j=0;
for(j=0;j<i;j++)
{//enter code here
cout<<a[j]<<" ";
}
//getch();
return 0;
}
Related
How do I accept an unknown number of lines in c++? Each line has two strings in it separated by a space. I tried the solutions mentioned in This cplusplus forum, but none of the solutions worked for me. One of the solutions works only when Enter is pressed at the end of each line. I am not sure if the \n char will be given at the end of my input lines. What are my options?
My current attempt requires me to press Ctrl+Z to end the lines.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line;
while(cin>>line and cin.eof()==false){
cout<<line<<'\n';
}
return 0;
}
I would like to take an unknown number of strings as shown below:
cool toolbox
aaa bb
aabaa babbaab
Please don't flag this as a duplicate, I really tried all I could find! I tried the following solution on the above given link by m4ster r0shi (2201), but it did not work for me.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
string word;
string line;
// get the whole line ...
getline(cin, line);
// ... then use it to create
// a istringstream object ...
istringstream buffer(line);
// ... and then use that istringstream
// object the way you would use cin
while (buffer >> word) words.push_back(word);
cout << "\nyour words are:\n\n";
for (unsigned i = 0; i < words.size(); ++i)
cout << words[i] << endl;
}
And this other solution also did not work: other soln, and I tried this SO post too: Answers to similar ques. This one worked for my example, but when I pass only one line of input, it freezes.
// doesn't work for single line input
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line ="-1";
vector<string>data;
while(1){
cin>>line;
if(line.compare("-1")==0) break;
data.push_back(line);
line = "-1";
}
for(int i =0;i<data.size();i+=2){
cout<<data[i]<<' '<<data[i+1]<<'\n';
}
return 0;
}
If each line has two words separated by whitespace, then perhaps you should have a Line struct which contains two std::strings and overloads the >> operator for std::istream.
Then you can just copy from std::cin into the vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
struct Line {
std::string first;
std::string second;
};
std::istream& operator>>(std::istream& i, Line& line) {
return i >> line.first >> line.second;
}
int main() {
std::vector<Line> lines;
std::copy(
std::istream_iterator<Line>(std::cin),
std::istream_iterator<Line>(),
std::back_inserter(lines)
);
for (auto &[f, s] : lines) {
std::cout << f << ", " << s << std::endl;
}
return 0;
}
A test run:
% ./a.out
jkdgh kfk
dfgk 56
jkdgh, kfk
dfgk, 56
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
ifstream inFile("registration.txt");
ofstream outFile("replaced.txt");
ifstream readFile("registration.txt");
vector<vector<string> > table;
if (inFile.is_open())
{
string line;
while( getline(inFile,line) )
{
stringstream ss(line);
vector<string> separated_fields;
cout<<line<<endl;
cout<<"----"<<endl;
string ID, fname, lname;
getline(ss,ID,',');
separated_fields.push_back(ID);
getline(ss,fname,',');
separated_fields.push_back(fname);
getline(ss,lname,',');
separated_fields.push_back(lname);
//vector<string> enrolled;
string course;
while( getline(ss,course,',') )
{
// cout<<"loop"<<endl;
separated_fields.push_back(course);
}
cout<<separated_fields[0];
cout<<"\n";
table.push_back(separated_fields);
}
}
cout<<"------------------"<<endl;
// cout<<table.size();
//cout<<table[0].size()<<endl;
for(int i=0 ;i<table.size();i++){
for(int j=0 ;j<table[0].size();j++){
cout<<table[i][j]<<"\t\t";
}
cout<<endl;
}
return 0;
}
I was able to print everything in the file but i couldn't change the character. i tried to do search and replace but u couldn't too. there is a vector of vectors called table that contain all the lines of the file.
There is a dedicated function in C++ to replace something in a string by something else. It is called: std::regex_replace. The description can be found here
See some example code below:
#include <iostream>
#include <string>
#include <regex>
int main() {
const std::string test = "a + b a+b +++ + + +plus+";
std::cout << std::regex_replace(test, std::regex(R"(\+)"), "plus");
return 0;
}
But, from your description, I do not exactly know . . .
/* In the text file I have a char followed by a blankspace then a string. I'm trying to read the char and string into seperated arrays. Any help is appreciated */
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char arrivOrDepart;
string licensePlt;
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
for (int i = 0; i < 4; i++)
{
getline(cin, arrivOrDepart[i]);
getline(cin, licensePlt[i]);
}
inFile.close();
cin.get();
return 0;
}
//text file
A QWE123
A ASD123
A ZXC123
A WER123
A SDF123
#include <fstream>
#include <iterator>
#include <vector>
this reads from file into vector
std::ifstream input("d:\\testinput.txt");
std::vector<std::string> bytes(
(std::istreambuf_iterator<std::string>(input)),
(std::istreambuf_iterator<std::string>()));
input.close();
then, just put the data into whatever container you want. you should almost always prefer vector over array btw
There are a few problems with the code:
getline is the wrong tool of choice for this. if you want to split a stream based on spaces, use >>.
arrivOrDepart and licensePlt are not defined as arrays but are used as arrays.
reading from cin, not from file.
My suggested fixes (excluding using vectors instead of arrays):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std; // avoid using this
int main()
{
const int MAXARRAY = 4; // avoid using magic numbers
char arrivOrDepart[MAXARRAY]; // made an array, but prefer std::vector
string licensePlt[MAXARRAY]; //made an array
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
string temp;
int i = 0;
while (i < MAXARRAY && // not overrunning the arrays
inFile >> temp >> licensePlt[i] && // read data from file stream
temp.length() == 1) // read only one character for arrivOrDepart
{
arrivOrDepart = temp[0];
i++;
}
inFile.close();
cin.get();
return 0;
}
Recommended reading:
Why is "using namespace std" considered bad practice?
What is a magic number, and why is it bad?
std::vector documentation (Alternate easier to read but often less accurate documentation)
std::getline documentation. Note the third parameter used to set the parsing delimiter.
I need to find a way of reading in the last 6 lines of data from a file.
For example if I have
1
2
3
4
5
6
7
8
9
10
I need to read be able to get
10, 9, 8, 7, 6, 5, 4.
These need to then be put into variables or strings to be outputted later. Currently I have managed to read in the last line of the file but I have no idea how to then read in the other 5 numbers.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
std::ifstream in("test.txt");
if (in.is_open())
{
std::vector<std::string> lines_in_reverse;
std::string line, line2;
while (std::getline(in, line))
{
// Store the lines in reverse order.
lines_in_reverse.insert(lines_in_reverse.begin(), line);
}
cout << line << endl;
while (std::getline(in, line2))
{
// Store the lines in reverse order.
lines_in_reverse.insert(lines_in_reverse.begin(), line2);
}
cout << line2 << endl;
}
cin.get();
return 0;
}
Can anyone advise a way to this? I do not know of any functions or methods that can help.
EDIT
This method outputs the last 6 numbers from the file however they are backwards and I need a way to reverse them and get rid of the whitespace it prints out.
I'm unsure on how to use reverse and which arguments are required from this - http://en.cppreference.com/w/cpp/algorithm/reverse
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
char x;
ifstream f("test.txt", ios::ate);
streampos size = f.tellg();
for (int var = 1; var <= size; var++){
f.seekg(-var, ios::end);
f.get(x);
reverse(x);
cout << x;
}
cin.get();
return 0;
}
Alot of the responses show me how to reverse the text file using vectors but not the last 6 numbers which is the only information I need.
Regards
It's not a good idea to store all the lines you read in, because there can be e.g. a billion lines.
You only need to store the last 6.
The following code is designed to produce those lines in reverse order, as the question indicates that is a requirement:
#include <iostream>
#include <string>
#include <deque>
using namespace std;
auto main() -> int
{
string line;
deque<string> last_lines;
while( getline( cin, line ) )
{
if( last_lines.size() == 6 )
{
last_lines.pop_back();
}
last_lines.push_front( line );
}
for( auto const& s : last_lines )
{
cout << s << endl;
}
}
The output here is not exactly the question's example
” 10, 9, 8, 7, 6, 5, 4
because that's 7 lines, contradicting the 6 that's stated in the first sentence.
How to read a file and print it reverse, in only three statements of code (excluding declarations and other boilerplate):
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
void read_and_print_reverse_n(std::istream& is, const int n)
{
std::vector<std::string> v;
// This call reads all whitespace-delimited "words" from the input stream
// and appends them to the vector
std::copy(std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(v));
// Output the last `n` lines from the input
for (const auto i = v.rbegin();
i < v.rend() && i < v.rbegin() + n;
++i)
{
std::cout << *i << '\n';
}
}
int main()
{
read_and_print_reverse_n(std::cin, 6);
}
References
std::copy
std::istream_iterator
std::back_inserter
I think the answer here would solve the purpose where you store the lines in a vector and iterate the vector from the end.
As you are looking for some direct method to read the file, you can read the file character by character starting from the end using seekg and tellg.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char x;
ifstream f("filename.txt",ios::ate);
streampos size = f.tellg();
for(int var=1;var<=size;var++){
f.seekg(-var,ios::end);
f.get(x);
printf("%c",x);
}
return 0;
}
You can also keep a count of \n to keep a track of the number of lines read from the end.
I want to put some text from a text file into an array, but have the text in the array as individual characters.
How would I do that?
Currently I have
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string line;
ifstream myfile ("maze.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
// --------------------------------------
string s(line);
istringstream iss(s);
do
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
} while (iss);
// ---------------------------------------------
}
myfile.close();
}
else cout << "Unable to open file";
system ("pause");
return 0;
}
I'm guessing getline gets one line at a time. Now how would I split that line into individual characters, and then put those characters in an array?
I am taking a C++ course for the first time so I'm new, be nice :p
std::ifstream file("hello.txt");
if (file) {
std::vector<char> vec(std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>()));
} else {
// ...
}
Very elegant compared to the manual approach using a loop and push_back.
#include <vector>
#include <fstream>
int main() {
std::vector< char > myvector;
std::ifstream myfile("maze.txt");
char c;
while(myfile.get(c)) {
myvector.push_back(c);
}
}