1

I am unable to get the part of the string stored in form of char array.

char code1 [12]={0};
char c;
string compressed_file;

I am taking the input from a text file, till a ',' occurs in it.

cout<<"Input compressed_file name"<<endl;
cin>>compressed_file;
string extracted_file;
cout<<"Input extracted_file name"<<endl;
cin>>extracted_file;

ifstream input;
input.open(compressed_file.c_str());
ofstream decompresscode;
decompresscode.open(extracted_file.c_str());

input>>c;
while(c != ',')
{
    int i=0;
    code1[i]=c;
    cout<<code1[i];
    i++;
    input>>c;
}
int old=atoi(code1);
cout<<old;

After printing the value of code1 here, I am only getting the first letter of the array. My code1 is 66, it is printing only 6.

1
  • Consider using an std::vector<char> instead of your array. This enables longer input and you would not need the variable i, select the back() element instead. Commented Oct 6, 2014 at 16:10

2 Answers 2

5

You are always saving in the position 0:

int i=0; // this need to be out of while loop
code1[i]=c;
cout<<code1[i];

You need also to add a check for read at max 12 char (to not overflow code1). The code could be something like.

input >> c;
int i = 0;
while (c != ',' && i < sizeof(code1)) {
    code1[i] = c;
    cout << code1[i];
    i++;
    input >> c;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Move int i = 0 outside the loop. As it is, you are resetting it to 0 each time.

input>>c;
int i=0; //move to here
while(c != ',')
{        
    code1[i]=c;
    cout<<code1[i];
    i++;
    input>>c;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.