[英]How to detect you've reached the end of a fgets string of integers, when 0 is the last integer in the line, using c++?
If I'm reading in lines from a .txt file of varying length, (ie 5 integers on line 1, then 2 integers on line 2, then 10 integers on line 3, and etc.), using fgets (although I don't necessarily need to use it, just seemed like a good tool in my situation). 如果我从不同长度的.txt文件中读取行(例如,第1行为5个整数,然后在第2行为2个整数,然后在第3行为10个整数,依此类推),则使用fgets(尽管我不这样做)不一定需要使用它,就我而言,这似乎是一个很好的工具)。 Every solution I find returns an error of 0 (like strtol or atio).
我找到的每个解决方案都返回错误0(如strtol或atio)。
char str[100];
char* p = str;
FILE* fp;
fp = open("text.txt",r);
if(fp == NULL)
printf("aborting.. Cannot open file! \n");
while(!foef(fp))
{
if(fgets(p,100,fp) != NULL)
{
for (int j = 0 ; j < 20 ; j+=2)
{
temp1 = strtol(p, &p, 10);
// need to store temp1 into arr[j] if it is a valid integer (0->inf)
// but should discard if we are at the end of the line
}
}
You could actually use C++: 您实际上可以使用C ++:
std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
int i;
while (iss >> i) {
// ...
}
}
The inner loop could simply load all of the ints into a vector directly or something: 内部循环可以直接将所有int直接加载到向量中或其他方式:
std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
std::vector<int> all_the_ints{
std::istream_iterator<int>{iss},
std::istream_iterator<int>{}
};
}
Ben's answer was so good, it should be part of the answer 本的答案很好,应该成为答案的一部分
Set errno to 0 before calling strtol. 在调用strtol之前将errno设置为0。
Check errno. 检查errno。 From man page
从手册页
ERANGE ERANGE
The resulting value was out of range. 所得值超出范围。 The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned) .
如果没有执行转换(没有看到数字,并且返回0),则该实现还可以将errno设置为EINVAL。
You're throwing away the information available from strtol
. 您将丢弃
strtol
可用的信息。
In particular, after a call 特别是通话后
val = strtol(p, &endp, radix);
you are interested in whether p == endp
. 您对
p == endp
是否感兴趣。
In your call strtol(p, &p, radix)
you're overwriting p
too soon and losing the chance to perform the test. 在调用
strtol(p, &p, radix)
您太早覆盖了p
并失去了执行测试的机会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.