简体   繁体   English

是否可以从c ++文件的一行中的特定字符中读取?

[英]is it possible to read from a specific character in a line from a file in c++?

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 人口规模:30

Is there any way in c++ that I can read from after the ':'? 在c ++中,有什么方法可以让我在':'之后读取? 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. 给我很多错误,因为由于某种原因它不想直接写到字符串。.我真的不想使用char数组,因为那样测试数字并从中提取出来就不那么容易了。字符串。 So is there anyway I can use the getline function with a string? 因此,无论如何,我可以将getline函数与字符串一起使用吗? 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. 好的,这是我的带有新getline的代码,但是它仍然不输出任何内容。 it does correctly open the text file and it works with a char array 它确实可以正确打开文本文件,并且可以使用char数组

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 显然,这一切都取决于您要对数据做些什么

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM