是否可以从c ++中的文件中的一行中的特定字符读取? [英] is it possible to read from a specific character in a line from a file in c++?

查看:121
本文介绍了是否可以从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:

人口规模:30

在c ++中有什么方法可以在':'之后读取?
我试过使用>>运算符like:

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

string pop;
inFile >> pop;

但是当然,空格在语句到达数字之前终止语句, p>

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

inFile.getline(pop, 20);

给我一​​些错误,因为它不想直接写入字符串。 b $ b我真的不想使用一个字符数组,因为它不会那么容易测试的数字,并从字符串中提取。
那么还有什么我可以使用getline函数与字符串?
可以从':'字符之后读取?

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这里是我的代码与新的getline, 。它确实正确地打开了文本文件,并且使用了一个char数组。

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

推荐答案

你最好阅读整行,字符串: -

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

你可能更好找冒号: / p>

You are probably better too looking for the colon :-

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

或类似的

一旦你这样做,你可能想把它回馈到字符串流,这样你可以读int和东西?

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

这篇关于是否可以从c ++中的文件中的一行中的特定字符读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆