D.I.C Head

Joined: 22 Oct, 2007
Posts: 51

My Contributions

I am little confused here. So please help me.
I am given a txt file in the following format

110001 + 123500

I need to read these numbers into the source file, do the addition and then print the result.

My approach was to use a for loop to read a character at a time until an operator such as '+' is found. Store that number into a var1, then continue reading after the operator symbol '+' until new line is approached. Store that number into var2.
Then add var1+ var2.

But what will be my parameters for for loop. I mean
for (i = 0; i <= ? ; i++);

Appreciate your help guys.

7 Years
Discussion Span
Last Post by rbv

Use a while loop instead.

Also, the for loop is a lot more flexible than "count from 0 to N". The syntax is:

for ( initialize ; condition ; update ) controlled_statement_or_block

condition can be anything, not just i <= N.

For example, looping through a string often looks like:

for ( char* pch = s; *pch; pch++ ) { ... }

When *pch is false (zero, aka NUL character), the loop exits.

But I think you will have more understandable code if you use a while loop.


Why use a for loop and looping through every character when you have predefined functions for that...???

You are reading the inputs form a text file right,just do this :

ifstream file;
file.open(<your filename>);
char str1[10],str2[10];

Now you have the two values you wanted in str2 and str2.Use some function such as strtol to get the integer value from the string and use for your addition.

Your way of looping through every character is a complete waste when you have your file something as:

// 1000 or more such records.

So try to use the predefined functions.

Edited by csurfer: n/a


When he says "an operator such as '+'", I'm forced to believe the file looks more like:

// 1000 or more such records.

Just extract integers from the file, then use eatwhite or the ws modifier and character reads. Forget about getline since you don't know the separator.

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.