簡體   English   中英

讀入數字但停在負C ++

[英]Read in Numbers but Stop at Negative C++

我想做的是從文本文件(當前稱為“輸入”)中讀取數字。 我正在創建兩個數組,一個數組用於整數,一個數組用於浮點數。 數組中的最大項數設置為50,但是最小值是1。程序停止讀取數字的標識符是int值中的任何負數。

我不確定為什么,但是當我讀回數組時,會打印出數字,跳過最后的負數,然后為剩余的插槽(最多50個)打印出亂碼。

任何意見,將不勝感激。

void Read(ifstream &input, int studentID[], float score[])
{
    int curID;
    float curScore;
    for (int i = 0; i < 50; i++)
    {
        input >> curID >> curScore;
        if (curID < 0)
        {
            return;
        }
        else
        {
            studentID[i] = curID;
            score[i] = curScore;
        }
    }
}
if (curID < 0)
{
    return;
}

這是因為如果遇到負數,則算法不會將該負數存儲在studentID[i]

結果, studentID仍然從第一個無效位置開始包含未初始化的值。 沒有魔力標記,也沒有計數器返回,您將無法重構輸入的結尾。

更正您的代碼

int Read(ifstream & input, int studentID[], float score[])
{
    int curID, i = 0;
    float curScore;
    while (i < 50) {
        input >> curID >> curScore;
        if (curID < 0)
            break;
        else {
            studentID[i] = curID;
            score[i++] = curScore;
        }
    }
    return i;    // This value will be useful while printing the contents
}

為避免產生混亂的輸出,僅迭代直到成功讀取為止,即返回Read(...)方法。

暫無
暫無

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

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