【问题标题】:c++ Read two words from text file into single char arrayc ++从文本文件中读取两个单词到单个字符数组中
【发布时间】:2014-11-07 01:20:39
【问题描述】:

我正在尝试从 .txt 文件中读取“名字姓氏”。这是我拥有的代码(它不起作用,它只复制第一个单词),它最终会弄乱我的整个程序。我怎样才能解决这个问题。拜托,只有有用的回复

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

//Structs
struct card {
  char suit[8];
  char rank[6];
  int cvalue;
  char location;
};

struct player {
  char name[100];
  int total;
  card hand[];
};

int main() {
  player people[4];
  /open player names file
  ifstream fin2;
  fin2.open("Players.txt");
  // check if good
  if (!fin2.good()) {
    cout << "Error with player file!" << endl;
    return 0;
  } else {
    int j = 0;
    fin2 >> people[j].name;  //prime file
    while (fin2.good()) {
      j++;
      fin2 >> people[j].name; //copy names into people.name
    }
  }
}

【问题讨论】:

  • people 声明在哪里?
  • Players.txt 文件是什么样的?
  • 我们是people
  • people 在 main 下被声明。不要问你自己能回答的问题

标签: c++ arrays io


【解决方案1】:

在文本文件上使用输入流运算符 (>>) 将读取直到遇到第一个空格(即空格、制表符、换行符)。您的代码fin2 &gt;&gt; people[j].name 只会从文件中读取第一个单词,因此您需要再次执行此操作才能获取第二个单词。但是,如果您只做两次相同的事情,您最终会得到第二个单词,因为它会覆盖第一个单词。你可以这样做:

fin2 >> people[j].name;       // read first name
n = strlen(people[j].name);   // get length of first name
people[j].name[n] = ' ';      // insert the space
fin2 >> &people[j].name[n+1]; // read last name

或者,如果每一行只有一个名字,你可以使用getline()函数。

getline(fin2, people[j].name);

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 2018-09-28
    • 2016-02-12
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多