is it possible to read from a specific character i

2019-07-14 17:50发布

问题:

Hey all so I have to get values from a text file, but the values don't stand alone they are all written as this:

Population size: 30

Is there any way in c++ that I can read from after the ':'? I've tried using the >> operator like:

string pop;
inFile >> pop;

but off course the whitespace terminates the statement before it gets to the number and for some reason using

inFile.getline(pop, 20);

gives me loads of errors because it does not want to write directly to string for some reason.. I don't really want to use a char array because then it won't be as easy to test for the number and extract that alone from the string. So is there anyway I can use the getline function with a string? And is it possible to read from after the ':' character?

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;
int main()
{
    string fname;
    cin >> fname;
    ifstream inFile;
    inFile.open(fname.c_str()); 
    string pop1;
    getline(inFile,pop1);
    cout << pop1;
    return 0;
}

ok so here is my code with the new getline, but it still outputs nothing. it does correctly open the text file and it works with a char array

回答1:

You are probably best to read the whole line then manipulate the string :-

std::string line;
std::getline(inFile, line);
line = line.substr(19);  // Get character 20 onwards...

You are probably better too looking for the colon :-

size_t pos = line.find(":");
if (pos != string::npos)
{
    line = line.substr(pos + 1);
}

Or something similar

Once you've done that you might want to feed it back into a stringstream so you can read ints and stuff?

int population;
std::istringstream ss(line);
ss >> population;

Obviously this all depends on what you want to do with the data



回答2:

Assuming your data is in the form

 <Key>:<Value>

One per line. Then I would do this:

std::string line;
while(std::getline(inFile, line))
{
    std::stringstream  linestream(line);

    std::string key;
    int         value;

    if (std::getline(linestream, key, ':') >> value)
    {
        // Got a key/value pair
    }
}