所有这些都发生在我的单循环中。 我为X,Y和3字符串创建临时变量。
文本文件有320行,如下所示:
1 2 "string" "stringy" "stringed"
int1 int2 string1 string2 string3
int1 int2 string1 string2 string3
int1 int2 string1 string2 string3
int1 int2 string1 string2 string3
循环代码在这里:
for(int Y = 0;Y < 320 ;Y++)
{
int tempX;
int tempY;
char tempRegionName;
char tempTXTfile;
char tempIMGfile;
fscanf(FileHandle, "%d %d %s %s %s ", &tempX, &tempY, &tempRegionName, &tempTXTfile, &tempIMGfile);
cout<<"X: "<<tempX<<" Y: "<<tempY<<" Name: "<<tempRegionName<<" TXT: "<< tempTXTfile << " IMG: " << tempIMGfile << endl;
}
当我调试时,让我们说它读取的行是:
1 2 "string" "stringy" "stringed"
然后这样做。
tempX = 1
tempY = 2(tempX现在为0)
tempRegionName =“string”(tempY现在为0)
tempTXTfile =“stringy”(tempReginoName现在为空)
tempIMGfile =“stringed”(tempTXTfile现在为空)。
然后输出:
X: 1 Y: 0 NAME: TXT: IMG: stringed
我不明白这一点。我尝试按照我在使用fscanf时找到的示例,另一个代码示例使用%d:%d。我尝试用:替换空格,但显然不是白色空间。
在cplusplus上查一下,我对理解有点困难。也许我只是累了,但我做错了什么?
答案 0 :(得分:1)
缓冲区不足以容纳字符串,即char
只有一个字节。您应该将变量声明为字符数组。例如,请尝试这样做:
for(int Y = 0;Y < 320 ;Y++)
{
int tempX;
int tempY;
char tempRegionName[64];
char tempTXTfile[64];
char tempIMGfile[64];
但请注意%s和目标缓冲区的大小。写“越界”很容易。