简体   繁体   English

用c ++扫描文件中的信息

[英]Scanning information from file in c++

I have a file with the following information: 我有一个包含以下信息的文件:

INTERSECTIONS:
1   0.3 mountain and 1st
2   0.9 mountain and 2nd
3   0.1 mountain and 3rd

How do I scan in c++ so that it scans the first number and stores it in an int, then scans the next number and stores it separately, then stores the name of the streets in an a string? 如何在c ++中扫描以便扫描第一个数字并将其存储在int中,然后扫描下一个数字并将其单独存储,然后将字符串的名称存储在字符串中? I just switched from c so I know how to do it in C just by using 我刚刚从c切换,所以我知道如何在C中使用它

fscanf("%d %lf %s", int, float, string);

or 要么

fgets 与fgets

with strings but don't know how to do this in C++. 使用字符串但不知道如何在C ++中执行此操作。 Any help would be appreciated 任何帮助,将不胜感激

main: 主要:

#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);
            }

            }
        }
}   

It's enough with std::getline and std::istringstream and the standard C++ stream input operator: 使用std::getlinestd::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);
}

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

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