我有一个包含以下信息的文件:
INTERSECTIONS:
1 0.3 mountain and 1st
2 0.9 mountain and 2nd
3 0.1 mountain and 3rd
如何在c ++中扫描以便扫描第一个数字并将其存储在int中,然后扫描下一个数字并将其单独存储,然后将字符串的名称存储在字符串中?我刚刚从c切换,所以我知道如何使用
在C中完成它fscanf("%d %lf %s", int, float, string);
或
与fgets
使用字符串但不知道如何在C ++中执行此操作。任何帮助将不胜感激
主:
#include<iostream>
#include<list>
#include <fstream>
#include<cmath>
#include <cstdlib>
#include <string>
#include "vertex.h"
#include "edge.h"
#include "global.h"
using namespace std;
int main ( int argc, char *argv[] ){
if(argc != 4){
cout<< "usage: "<< argv[0]<<"<filename>\n";
}
else{
ifstream map_file (argv[3]);
if(!map_file.is_open()){
cout<<"could not open file\n";
}
else{
std::string line;
std::ifstream input(argv[3]);
int xsect;
int safety;
std:string xname;
std::list<vertex> xsection;
std::list<edge> EdgeList;
while (std::getline(input, line))
{
std::istringstream iss(line);
iss >> xsect >> safety;
std::getline(iss, xname);
}
}
}
}
答案 0 :(得分:4)
std::getline
和std::istringstream
以及标准C ++流输入运算符就足够了:
std::string line;
std::ifstream input(...);
while (std::getline(input, line))
{
std::istringstream iss(line);
int v1;
double v2;
std::string v3;
iss >> v1 >> v2;
std::getline(iss, v3);
}