【发布时间】:2014-09-16 00:15:06
【问题描述】:
我正在尝试将文本文件中的两个单词读入一个 char 数组元素。我不能使用 std::string。我得到一个段错误,因为我的循环以超出范围的方式循环。我无法复制这两个词。请帮我做这个!我的卡片结构循环完美运行。我无法将“第一个最后一个”放入 people[].name // 卡片组 // 下面是初始化 #包括 #包括 #包括 #包括 #包括
using namespace std;
//globals
const int maxCards = 52;
//Structs
struct card {
char suit[8];
char rank[6];
int cvalue;
char location;
};
struct player {
char name[100];
int total;
card hand[4];
};
//program
int main()
{
//constants
char tempfName[100];
char templName[100];
//create struct array(s)
card deck[52];
card shuffledDeck[52];
player people[4];
//create pointers
card * deckPointer =NULL;
deckPointer = deck;
card * shuffledDeckPointer=NULL;
shuffledDeckPointer = shuffledDeck;
for(int i=0;i<4;i++)
{
strcopy(people[i].name,"first last");
}
//open player names file
ifstream fin2;
string fin2Name;
//get file name from user
cout << "Enter player file name...(Players.txt)" << endl;
getline(cin, fin2Name);
//open file
fin2.open(fin2Name.c_str());
//check if Players.txt opens correctly
if(!fin2.good())
{
cout << "Error with player file!" << endl;
return 0;
}
else
{
int j =0;
fin2 >> people[j].name; //prime file
while(fin2.good())
{
//find the length
int index =0, length=0;
while(tempfName[length] != '\0')
{
length++;
}
//now add space after first name
tempfName[length] = ' ';
length++;
while(templName[index] != '\0')
{
tempfName[length] = templName[index];
length++;
index++;
}
tempfName[length]='\0';
int counter =0;
while(templName[counter] != '\0')
{
people[0].name[counter] = templName[counter];
counter++;
}
}
}
【问题讨论】:
-
"I CANNOT USE std::string" - 如果你要那么强调它,你不妨说为什么。而
while(fin2.good())和while(!fin2.eof())一样错,你可以read about here -
请减少您显示的代码量,只显示与您的问题相关的行。
-
fin2.good 和 fin.good 一样有效。感谢您的回复和解决 绝对没有任何相关信息
-
我建议您阅读位于
<cstring.h>中的str*()函数。您应该使用strcat,而不是编写循环来复制单个字符。您还可以使用strchr在 C 样式字符串中查找字符。 -
我读了你的代码。您是否出于同样的礼貌并费心阅读我提供的链接?如果你不能使用
std::string什么是fin2Name?您想要相关信息吗?您是否打算从fin2中读取一个 项?如果你进入你的whilebody,当你再也没有接触过流时,你期望打破 `while(fin2.good())` 怎么办?
标签: c++