C++从文本文件中读取两个单词到单个字符数组
我正在尝试从.txt文件中读取firstname lastname。这是我的代码,它不起作用,它只复制了第一个单词,最终把我的程序搞砸了。我怎样才能解决这个问题。请,只有有用的答复C++从文本文件中读取两个单词到单个字符数组,c++,arrays,io,C++,Arrays,Io,我正在尝试从.txt文件中读取firstname lastname。这是我的代码,它不起作用,它只复制了第一个单词,最终把我的程序搞砸了。我怎样才能解决这个问题。请,只有有用的答复 #include <fstream> #include <iostream> using namespace std; //Structs struct card { char suit[8]; char rank[6]; int cvalue; char location;
#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
}
}
}
在文本文件上使用输入流操作符>>将一直读取,直到遇到第一个空格,即空格、制表符、换行符。您的代码fin2>>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);
在哪里声明people?Players.txt文件是什么样子的?我们就是people.people就在main下面声明。不要问你能自己回答的问题