C++ read file until '%' character

时间:2015-07-08 15:57:48

标签: c++

I am writing a program in which I am getting input form a text file. I want to read the file until I found this '%'. Currently, the break statement is not working and I am reading in the entire text file.

Here is my code:

#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;
    }
}

input file :

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

What I want is to read file until %.

4 个答案:

答案 0 :(得分:3)

This is because you check data[i] before reading data into it. Just put if check after the file >> data[i]:

file >> data[i];

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

cout << data[i];

答案 1 :(得分:1)

You check data[i] before it's initialized. Local variables, including arrays, are not initialized, their value is indeterminate (and will seem random), reading from an uninitialized local variable leads to undefined behavior.

What you need to do is to read data first, then check if the character was what you were looking for.

答案 2 :(得分:0)

Switch the two lines:

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

To

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

答案 3 :(得分:0)

您的问题在于

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

data[i]的内容是什么?现在,这将导致undefined behavior。你可以通过做两件事来解决这个问题。首先,当你创建数组时,将它归零,以便它将充满空字符(不再是UB!)

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

然后,在循环中,将下一个字符读入临时变量,并检查临时变量。您的问题是在阅读之前检查:

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 
}