Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从文本文件读取并分配给单独的变量名_C++ - Fatal编程技术网

C++ 从文本文件读取并分配给单独的变量名

C++ 从文本文件读取并分配给单独的变量名,c++,C++,我的文本文件类似于: title=mr name=John Abrahm country=USA age=30 gender=M 约翰·阿布拉姆先生,美国,30岁,男 哈里先生,英国,40岁,男 杰克先生,美国,50米 我想这样做: title=mr name=John Abrahm country=USA age=30 gender=M 到目前为止,我的代码如下: ifstream inputFile("text.txt"); string line; wh

我的文本文件类似于:

title=mr  
name=John Abrahm  
country=USA  
age=30  
gender=M
约翰·阿布拉姆先生,美国,30岁,男
哈里先生,英国,40岁,男
杰克先生,美国,50米

我想这样做:

title=mr  
name=John Abrahm  
country=USA  
age=30  
gender=M
到目前为止,我的代码如下:

ifstream inputFile("text.txt");
string line;
while (getline(inputFile, line))
{
    istringstream ss(line);

    string title;
    string name;
    string country;
    char gender;

    ss >> title>>nam>>age>>country>>gender;
    cout <<gender<< endl;
}
ifstream输入文件(“text.txt”);
弦线;
while(getline(inputFile,line))
{
istringstream ss(线);
字符串标题;
字符串名;
弦国;
性别;
ss>>标题>>不结盟运动>>年龄>>国家>>性别;
cout您可能正在寻找

示例代码:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="mr,John Abrahm,USA,30,M";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,");
  while (pch != NULL)
 {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,");
 }
 return 0;
}
不用打印字符串,你可以把它们分配给变量。你可能想看看这个

编辑:对于几行,假设您要提取5个不同数组中每行中的所有5个条目。首先执行以下操作:

pch1 = strtok (str," \n");
这将为您提供一个特定的行,您可以用它进一步划分

pch = strtok (pch1," ,");

这很可能只有嵌套循环。

欢迎访问StAccOffFult.com。请花些时间阅读,特别是命名的部分。请同时。请最后学习如何创建A。谢谢您的建议。但是,我使用C++,我的文件包含很多行(比如100)。@ AATANKA,我不明白为什么这是个问题。<代码> Strutok <代码>在C++中可用。只需要基本操作来扩展我的答案,请查看我的编辑。