i

closed account (iNApoG1T)
hi! i am

Last edited on
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;
}
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
  }
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?
rose00 wrote:
hi! i am
Last edited on

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!
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.