i
Apr 14, 2017 at 7:21am UTC
hi! i am
Last edited on Apr 14, 2017 at 8:04am UTC
Apr 14, 2017 at 7:35am UTC
If you want to read a file into a vector line by line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
std::ifstream file("filename.txt" );
std::vector<std::string> vec;
std::string line;
while (std::getline(file, line));
vec.push_back(line);
for (const std::string& line : vec)
std::cout << line << '\n' ;
return 0;
}
If you want to read a file into a vector word by word:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
std::ifstream file("filename.txt" );
std::vector<std::string> vec;
std::string word;
while (file >> word);
vec.push_back(word);
for (const std::string& word : vec)
std::cout << word << '\n' ;
return 0;
}
Apr 14, 2017 at 7:41am UTC
Normally you read a file like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
ifstream inputFile("travel.txt" );
if (!inputFile)
{
// handle error
return -1;
}
string word;
while (inputFile >> word) // read word by word
{
// use line
}
//or
string line;
while (getline(inputFile, line)) // read line by line
{
// use input
}
Apr 14, 2017 at 9:46am UTC
Thomas1965 wrote:1 2 3 4 5
if (!inputFile)
{
// handle error
return -1;
}
Forgot about error checking. Though wouldn't you normally use
!file.is_open()
to check if a file was not successfully opened?
Also, to the OP: Why did you delete everything in your original post and replace it with this?
Last edited on Apr 14, 2017 at 9:47am UTC
Apr 14, 2017 at 11:50am UTC
Also, to the OP: Why did you delete everything in your original post ...?
this is the most egregious behavior that we come across on this forum, idiots!
Apr 14, 2017 at 2:42pm UTC
Though wouldn't you normally use !file.is_open() to check if a file was not successfully opened?
There are different ways to check. You also could use if(!inputFile.fail())
Topic archived. No new replies allowed.