簡體   English   中英

C ++讀取文件直到'%'字符

[英]C++ read file until '%' character

我正在編寫一個程序,在該程序中我從文本文件獲取輸入。 我想讀取文件,直到找到“%”為止。 目前, break語句不起作用,我正在讀取整個文本文件。

這是我的代碼:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int main() {


     char data[1000]; 
     char c = '%';
     int securitykey = 0;

    ifstream file("data.txt");

    if(file.is_open())
    {

        for(int i = 0; i <= 493; ++i)
        {
            if(data[i]==c)break;

            file >> data[i];
            cout<< data[i];
          securitykey += (int)data[i]; 

        }
         cout <<securitykey;
    }
}

輸入文件 :

Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
%152365

我要讀取的文件直到%

這是因為您在讀取數據之前先檢查data[i] 只要把if檢查后file >> data[i]

file >> data[i];

if (data[i] == c)
    break;

cout << data[i];

您可以在初始化data[i]之前檢查data[i] 局部變量(包括數組)未初始化,其值是不確定的 (並且似乎是隨機的),從未初始化的局部變量讀取會導致未定義的行為

您需要做的是先讀取數據, 然后檢查字符是否正在尋找。

切換兩行:

if(data[i]==c)break;
file >> data[i];

file >> data[i];
if(data[i]==c)break;

你的問題是線

if(data[i]==c)break;

data[i]什么? 現在,這將導致不確定的行為 您可以通過做兩件事來解決此問題。 首先,在創建數組時,將其歸零,以使其充滿空字符(不再需要UB!)

char data[1000] = {0}; //fill data with 0's

然后,在循環中,將下一個字符讀入temp變量,然后檢查temp變量。 您的問題是您在閱讀之前先進行了檢查:

for(int i = 0; i <= 493; ++i)
{
    char temp;
    file >> temp;

    if(temp == c)break;       //If we found one, get out of there!

    data[i] = temp;           //If not, update data
    securitykey += (int)temp; //and security key 
}

暫無
暫無

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

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