簡體   English   中英

使用C ++,當行中的最后一個整數為0時,如何檢測到fgets整數字符串的末尾?

[英]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++?

如果我從不同長度的.txt文件中讀取行(例如,第1行為5個整數,然后在第2行為2個整數,然后在第3行為10個整數,依此類推),則使用fgets(盡管我不這樣做)不一定需要使用它,就我而言,這似乎是一個很好的工具)。 我找到的每個解決方案都返回錯誤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
}
}

您實際上可以使用C ++:

std::ifstream file("text.txt");
std::string line;
while (std::getline(file, line)) {
    std::istringstream iss(line);
    int i;
    while (iss >> i) {
        // ...
    }
}

內部循環可以直接將所有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>{}
    };
}

本的答案很好,應該成為答案的一部分

在調用strtol之前將errno設置為0。

檢查errno。 從手冊頁

ERANGE

所得值超出范圍。 如果沒有執行轉換(沒有看到數字,並且返回0),則該實現還可以將errno設置為EINVAL。

您將丟棄strtol可用的信息。

特別是通話后

val = strtol(p, &endp, radix);

您對p == endp是否感興趣。

在調用strtol(p, &p, radix)您太早覆蓋了p並失去了執行測試的機會。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM