Reading a Line from Ifstream into a String Variable

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

Reading a line from a file into different variables using fstream

The input operator >> separates on white-space. Instead you might want to use std::getline to read the semicolon separated fields.

Something like

std::string id_string, money_string;
while (std::getline(ClientsFile, id_string, ';') &&
std::getline(ClientsFile, name, ';') &&
std::getline(ClientsFile, money_string))
{
id = std::stoi(id_string);
money = std::stod(money_string);
...
}

Read file line by line using ifstream in C++

First, make an ifstream:

#include <fstream>
std::ifstream infile("thefile.txt");

The two standard methods are:

  1. Assume that every line consists of two numbers and read token by token:

    int a, b;
    while (infile >> a >> b)
    {
    // process pair (a,b)
    }
  2. Line-based parsing, using string streams:

    #include <sstream>
    #include <string>

    std::string line;
    while (std::getline(infile, line))
    {
    std::istringstream iss(line);
    int a, b;
    if (!(iss >> a >> b)) { break; } // error

    // process pair (a,b)
    }

You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline() after token-based extraction got you to the end of a line already.

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
std::string temp;
std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
std::string temp;
while(std::getline(file, temp)) {
//Do with temp
}

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

extract line of text into a variable string

You could:

  • read your input stream into a vector of lines, and
  • walk that vector of lines checking if it starts with a given city name;
  • copying those lines that do match to an output vector (or just printing them out, or whatever).

The example below:

  • uses a std::istringstream instead of a std::fstream as input, and
  • takes the walk of the input lines and the creation of the output vector to a filter_by_city function.

[Demo]

#include <algorithm>  // copy_if
#include <iostream> // cout
#include <iterator> // istream_iterator
#include <sstream> // istringstream
#include <string>
#include <string_view>
#include <vector>

auto filter_by_city(const std::vector<std::string>& lines, std::string_view city) {
std::vector<std::string> ret{};
std::copy_if(std::cbegin(lines), std::cend(lines), std::back_inserter(ret),
[&city](const auto& line) {
return line.substr(0, line.find(';')) == city;
});
return ret;
}

int main()
{
std::istringstream iss{"MILAN;F205\nROME;G306\nMILAN;H407\nFIRENZE;I508\n"};
std::vector<std::string> lines{std::istream_iterator<std::string>{iss}, {}};
for (auto&& line : filter_by_city(lines, "MILAN")) {
std::cout << line << "\n";
}
}

// Outputs:
//
// MILAN;F205
// MILAN;H407

A probably better option, considering your input file is a database, would be to:

  • read your input stream into a map of cities, and
  • query for a specific city.

[Demo]

#include <algorithm>  // transform
#include <iostream> // cout
#include <iterator> // istream_iterator
#include <map>
#include <sstream> // istringstream
#include <string>
#include <utility> // make_pair

auto create_db(std::istringstream& iss) {
std::map<std::string, std::string> ret{};
std::transform(std::istream_iterator<std::string>{iss}, {},
std::inserter(ret, std::end(ret)),
[](const auto& line) {
auto sep{ line.find(';') };
return std::make_pair(line.substr(0, sep), line.substr(sep + 1));
});
return ret;
}

int main()
{
std::istringstream iss{"MILAN;F205\nROME;G306\nNAPOLI;H407\nFIRENZE;I508\n"};
auto db{ create_db(iss) };
if (db.contains("MILAN")) {
std::cout << "MILAN: " << db["MILAN"] << "\n";
}
}

// Outputs:
//
// MILAN: F205

How do I read a file in C++ and write contents into a string?

Don't use << to append something in a string.

Rather than:

while (getline(shaderFile, line)) {
sourceCode << line;
}

Consider:

while (getline(shaderFile, line)) {
sourceCode += line;
}

How can I read lines from a text file into a variable

I managed to solve this by adding in if (line[0] != '/' && !line.empty()) { inside the while loop and creating a new string variable called lineArray[5]. The function now looks like this

    config openFile(std::string filename, config &con) {
std::fstream inputFile(filename.c_str(), std::fstream::in);
if (inputFile.is_open()) {
std::string line;
std::string lineArray[5];
int count = 0;
while (std::getline(inputFile, line)) {
if (line[0] != '/' && !line.empty()) {
lineArray[count] = line;
count++;
}
}
std::cout << "Printing out " << lineArray[0] << std::endl;

std::cout << std::endl;
return con;
}
else {
std::cout << "Unable to open file" << std::endl;
}
}

And the output I'll get is Printing out GridX_IdxRange=0-8.

I am using ifstream and I need to read in two words as one string instead of splitting them

I assume you are doing

  std::string nameString;
fs >> nameString;

this will read to the end of a word.
do this instead

 std::string nameString;
std::getline(fs, nameString);

this will read the whole line

How to read a file line by line to a string type variable?

Use std::getline:

std::string s;
while (std::getline(file, s))
{
// ...
}


Related Topics



Leave a reply



Submit