C++ 将两个单词读入一个字符数组元素
我试图将文本文件中的两个单词读入一个char数组元素。我不能使用std::string。我得到一个seg错误,因为我的循环以一种超出界限的方式循环。我不能抄这两个字。请帮我做这个!!我的卡片结构循环工作得很好。我无法将“第一个最后一个”输入人物[]。姓名 //一副牌 //下面是初始化 #包括 #包括 #包括 #包括 #包括C++ 将两个单词读入一个字符数组元素,c++,C++,我试图将文本文件中的两个单词读入一个char数组元素。我不能使用std::string。我得到一个seg错误,因为我的循环以一种超出界限的方式循环。我不能抄这两个字。请帮我做这个!!我的卡片结构循环工作得很好。我无法将“第一个最后一个”输入人物[]。姓名 //一副牌 //下面是初始化 #包括 #包括 #包括 #包括 #包括 using namespace std; //globals const int maxCards = 52; //Structs struct card { char
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++;
}
}
}
使用名称空间std;
//全球的
常量int maxCards=52;
//结构
结构卡{
半诉讼[8];
字符秩[6];
int值;
字符位置;
};
结构播放器{
字符名[100];
整数合计;
牌手[4];
};
//节目
int main()
{
//常数
char tempfName[100];
字符模板名称[100];
//创建结构数组
卡片组[52];
卡片洗牌[52];
玩家人[4];
//创建指针
卡片*deckPointer=NULL;
甲板指针=甲板;
卡片*shuffledDeckPointer=NULL;
shuffledDeckPointer=shuffledDeck;
对于(int i=0;i你可以做一些欺骗:
char full_name[256]; // Binary quantities are better.
snprintf(full_name, sizeof(full_name),
"%s %s",
first_name, last_name);
你应该对C风格的字符串函数做更多的研究,比如看一本好的参考书。书中应该有一章介绍C风格的字符串函数
以下是一些有用的建议:
strcpy、strcat、strchr、sprintf、strlen
在else语句中,tempfName似乎没有指向while循环中的正确对象
其他的
{
“我不能使用std::string”-如果你想强调这一点,你不妨说一下原因。while(fin2.good())
和while(!fin2.eof())一样错误
,您可以减少仅向问题相关行显示的代码量。fin2.good的工作原理与fin.good的工作原理相同。感谢您回复并解决绝对没有相关信息的问题。我建议您阅读str*()
函数位于
中。您应该使用strcat
而不是编写循环来复制单个字符。您还可以使用strcr
来查找C样式字符串中的字符。我阅读了您的代码。您是否也像我一样礼貌地阅读了我提供的链接?如果您不能使用std::string
什么是fin2Name
?您想要相关信息吗?您是否打算从fin2
中读取一项内容?如果您在while
正文中输入while,当您再也不接触流时,您希望打破'while(fin2.good())`什么?我们不允许使用这些函数
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++;
}