0

所有这些都发生在我的单循环中。我为 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"

然后它会这样做。

温度 X = 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 上查找它,我有点难以理解。也许我只是累了,但我做错了什么?

4

1 回答 1

1

缓冲区不足以容纳字符串,即char只有一个字节。您应该将变量声明为字符数组。例如,试试这个:

for(int Y = 0;Y < 320 ;Y++)
{
    int tempX;
    int tempY;
    char tempRegionName[64];
    char tempTXTfile[64];
    char tempIMGfile[64];

但要小心 %s 和目标缓冲区的大小。写“越界”很容易。

于 2013-10-21T14:05:40.137 回答