C++ 单行文本中读取字符串+整型问题

如何用C++从这一行txt文件中把vertex这个字符串存到比如X中,再把1放到Y中。再把 1 0 1分别放到a ,b ,c三个变量中

img

有详细代码讲解最好!

#include <iostream>
#include <fstream>
using namespace std;

typedef struct _data
{
    char  X[20];
    int Y;
    int a,b,c;
}data;

int main()
{
    ifstream inf;
    inf.open("D:\\test.txt", ifstream::in);
    string line;
    data rows[1000];
    int n=0;
    while (!inf.eof())
    {
        getline(inf,line);
        sscanf(line.c_str(),"%s%d%d%d%d",rows[n].X,&rows[n].Y,&rows[n].a,&rows[n].b,&rows[n].c);
        n++;
    }
    inf.close();
    for(int i=0;i<n;i++)
        cout<<rows[i].X<<" "<<rows[i].Y<<" "<<rows[i].a<<" "<<rows[i].b<<" "<<rows[i].c<<endl;
    return 0;
}

解答如下

img

#include <stdio.h>
#define MAX 255
#define FILE_PATH "file.txt"
//文件和代码放同一个目录 
int main()
{
    char X[MAX][MAX];//保存读取的字符串 
    int Y[MAX], a[MAX], b[MAX], c[MAX];//保存读取的数字 
    int count=0;//读取行数 
    FILE *fp;
    fp = fopen(FILE_PATH, "r");
    if(fp == NULL)
    {
        printf("ERROR\n");
    }
    else
    {
        while(fscanf(fp, "%s%d%d%d%d", X[count], &Y[count], &a[count], &b[count], &c[count])==5)
        { 
            printf("%s %d\t\t%d %d %d\n", X[count], Y[count], a[count], b[count], c[count]);
            count++;
        }
    }
    fclose(fp);
    return 0;
}
#include <stdio.h>

int main()
{
    char X[20];
    int Y, a, b, c;
    FILE *fp;
    fp = fopen("1.txt", "r"); //打开文件
    if(fp == NULL) {
        return -1;
    }
    while(!feof(fp)) {
        fscanf(fp, "%s %d %d %d %d", X, &Y, &a, &b, &c); //按格式读取文件内容
        printf("%s %d %d %d %d\n", X, Y, a, b, c); //输出每一行的内容
    }
    fclose(fp);
    return 0;
}

#include <stdio.h>
#define MAX 255
#define FILE_PATH "file.txt"
int main()
{
    char X[MAX][MAX];//保存读取的字符串 
    int Y[MAX], a[MAX], b[MAX], c[MAX];//保存读取的数字 
    int count=0;//读取行数 
    FILE *fp;
    fp = fopen(FILE_PATH, "r");
    if(fp == NULL)
    {
        printf("ERROR\n");
    }
    else
    {
        while(fscanf(fp, "%s%d%d%d%d", X[count], &Y[count], &a[count], &b[count], &c[count])==5)
        { 
            printf("%s %d\t\t%d %d %d\n", X[count], Y[count], a[count], b[count], c[count]);
            count++;
        }
    }
    fclose(fp);
    return 0;
}

希望能对你有所帮助

分割字符串,读取一行之后,对特定的分隔符,进行区分,隔出数据,在通过trim消除空格,这种做法比较智能。
如果用scanf 格式变固定了。
看你文件格式,如果固定的用scanf 然后用\t 空格进行格式定义,然后按照定义读取。

如何用C++从这一行txt文件中把vertex这个字符串存到比如X中,再把1放到Y中。再把 1 0 1分别放到a ,b ,c三个变量中

既然有固定格式, C++的标准做法就是流操作.

#include <fstream>
#include <iostream>

auto main() -> int
{
    // 初始化文件流
    std::ifstream file;

    // 打开文件
    file.open("fileName.txt");

    // 初始化变量
    std::string X;

    int Y;

    bool a;
    bool b;
    bool c;

    // 变量赋值
    while (file >> X >> Y >> a >> b >> c)
    {
        std::cout << X << Y << a << b << c << std::endl;
    }

    // 关闭流
    file.close();

    return 0;
}