我的文件的第一行必须是我读入firstline2的两位数。我使用sscanf从该缓冲区读取数据并将其存储到一个int中,以表示文件中的行数(不包括第一行)。如果有第三个字符,我必须退出并返回错误代码。
我尝试引入一个新的字符缓冲区thirdchar1,并将其与新行(10或'\n')进行比较。如果thirdchar不等于换行符,那么它应该退出并返回一个错误代码。在稍后的程序中,我使用sscanf读取firstline,并将该数字存储到一个名为numberoflines的int中。当我引入thirdchar时,它会将额外的两个零附加到numberoflines的第一行的末尾。
//If the first line was "20"
int numberoflines;
char firstline[2];
file.get(firstline[0]);//should be '2'
file.get(firstline[1]);//should be '0'
char thridchar[1];
file.get(thirdchar[0]);//should be '\n'
if (thirdchar !=10){exit();}//10 is the value gdb spits out to represent '\n'
sscanf(firstline, "%d", &numberoflines);//numberoflines should be 20
我调试过了,第一行和第三个字符是期望值,但是数字变成了2000!我已经删除了与thirdchar相关的代码,它工作得很好,但不符合它是一个2位数字的要求。我误解了sscanf的作用吗?有没有更好的方法实现这一点?谢谢。
因此,我更新了代码以使用std::string和std::getline:
std::string firstline;
std::getline(file, firstline);
当我尝试打印firstline的值时,我得到了以下错误
$1 = Python Exception <class 'gdb.error'> There is no member named _M_dataplus.:
发布于 2019-08-27 22:25:35
sscanf
要求输入字符串为null-terminated。您没有向它传递以null结尾的字符串,因此它的行为与预期不符。
正如所建议的,您最好使用std::getline
读取字符串,并将std::string
转换为整数。
https://stackoverflow.com/questions/57676641
复制相似问题