开发者

finding characters between integers

开发者 https://www.devze.com 2023-02-16 21:21 出处:网络
i wanna make开发者_如何学JAVA a progarm with c++ that take input from one file that contains information

i wanna make开发者_如何学JAVA a progarm with c++ that take input from one file that contains information like this:

physic 17
math 20
programming 10

if i want give integer in this file and i don't want characters like physic and etc what libraray should i include and what function should i use


When you use file stream like fstream and reading to string, you get one word from the stream. So try creating fstream s and:

fstream s("file.txt",ios::in);
string word;
int number;
s >> word;
s >> number;
// do something with 17 (you got it in number variable)
s >> word;
s >> number;
// do something with 20 (you got it in number variable)
//and so on...


Until the end of file -

  1. std::getline from the file. ( fstream to perform file operations )
  2. strtok the read string ( i.e., read line from the file ) based on space delimeter until end of line. ( cstring )
  3. Convert the second token to integer using atoi. ( cstdlib )


You'll need to write your on function for this. But I recall scanf having the ability to filter out characters/numbers by specifying the type.

http://www.cplusplus.com/reference/clibrary/cstdio/scanf/


I would probably do this with the digits_only facet I posted in a previous answer. The sequence would look like:

std::ifstream infile("whatever.txt");
infile.imbue(std::locale(std::locale(), new digits_only());

std::vector<int> numbers;
int temp;

while (infile >> temp)
    numbers.push_back(temp); // or use std::copy, if you prefer
0

精彩评论

暂无评论...
验证码 换一张
取 消