# C String processing

• October 14th, 2013, 10:16 PM
kay19
C String processing
Hello, my program was to allow the user to enter a value as a C string in the form: xxx,xxx,xxx,xxx,xxx.xx, where x can be any digit. Well, so far here is my attempt. I think the question is, would I have to implement a switch statement for the digits, the comma, and the decimal, so that when a user inputs, let say 52,000.00 the switch statements would read the 1st digit, checks for decimals/commas and if not, proceed to read 2nd digit, and repeat?

A bit overwhelmed with this work, but i'll still rework my coding, just looking for any advice/tips really.
Code:

#include <iostream>
#include <string>

int main() {
using namespace std;
char buffer[256];
char tempBuff[256] = {'\n'};
double result;
int count = 0;

cout << "Testing " << endl;

cout << "Enter Any integers: ";
cin.getline(buffer,256);

for(int i = 0; i < strlen(buffer); i++)
{
if(isdigit(buffer[i]))
{
tempBuff[count] = buffer[i];
count++;
}

}

if (atof(tempBuff) > 0) {
result = atof(tempBuff) / 2;

}

cout << endl <<  "The integer you put was: " << tempBuff << " And dividing the integers "<<
result << endl;

cin.ignore();
return 0;
}

• October 15th, 2013, 04:53 AM
Paul McKenzie
Re: C String processing
Quote:

Originally Posted by kay19
I think the question is, would I have to implement a switch statement for the digits, the comma, and the decimal, so that when a user inputs, let say 52,000.00 the switch statements would read the 1st digit, checks for decimals/commas and if not, proceed to read 2nd digit, and repeat?

You're supposed to have a plan first, and then write the code that fits the plan, not the other way around.

Second, you didn't state what the final goal of your program is. What do you do with this information you've gathered from the string?

Third, you have the wrong #include file. Nowhere in your code do you use std::string, but you #included <string>. The proper #include is this:
Code:

#include <cstring>
Your code uses "old-style" C strings, not C++ std::string. You also failed to #include <cctype> for the isdigit() function.

Regards,

Paul McKenzie
• October 15th, 2013, 04:54 AM
2kaud
Re: C String processing
1) tempBuff should be initialised to 0 not '\n' as 0 is the terminating char for a c string
2) result should be initialised to 0 as it's used in the cout statement and may not have been set in the proceeding if statement
3) the if (isdigit()...) statement can be extended to test for a '.' so that any char other than a digit or a '.' is ignored.
• October 15th, 2013, 10:13 AM
kay19
Re: C String processing
Thanks for the replies guys. I only made a diagram where it consisted of 1st, 2nd, and 3rd digits along with a comma and decimal. But yeah, i'll have to sketch/plan more before hand. Thanks for the tips