soniccool
soniccool

Reputation: 6058

Convert string to int if number

Below i have a code where i want to cin a certain values. In the event i cin a [ it should just ignore it. BUT in the event a user inserts a number and not a [ it should convert the char into an int and insert it into rows in the else function. How can i convert this char into an int and place it into rows?

    char ignoreChar;

    is >> ignoreChar;

    if(ignoreChar == '[')
    {
    }

    else
    {
    rows = ignoreChar;
    }

Upvotes: 1

Views: 351

Answers (5)

Thinker
Thinker

Reputation: 1

Sorry for the code that is much longer than might be. Below is an example code of "factorial counting" with entering symbols with their handling. I tried to show different possibilities. The only problem I see now in it that there is no any reaction if a user just hit the Enter without any symbols entered. It is my the very first post here, so I'm very sorry with any possible fonts, formatting and other nonsense. MaxNum = 21 was empirically defined for the unsigned long long int return type.

I've checked such input cases: abcde 2. -7 22 21

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>

unsigned long long int CalcFact( int p ) 
    { return p == 0 || p == 1 ? 1 : p*CalcFact(p-1); }

int main()
{
int MaxNum = 21, HowMany = 0, MaxAttempts = 5, Attempts = 0;
char AnyKey[] = "", *StrToOut = "The factorial of ", Num[3] = "";
bool IsOK = 0;

while( !IsOK && Attempts++ < MaxAttempts )
{
    std::cout << "Please enter an integer > 0 and <= 21: ";
    std::cin.width(sizeof(Num)/sizeof(char)); 
    std::cin >> Num;
    for( int Count = 0; Count < strlen(Num); Count++ )
        IsOK = isdigit(Num[Count]) ? true : false;
    if( IsOK )
    {
        if( !(atoi(Num) >= 0 && atoi(Num) <= MaxNum) )
            IsOK = false;
        else
        {
            for( int Count = 0; Count <= MaxNum; Count++ )
                {
                std::cout << StrToOut << Count << std::setfill('.') 
                << std::setw( Count < 10 ? 30 : 29 ) 
                << CalcFact(Count) << std::endl; 
                }
        }
    }
    if( !IsOK && Attempts > 0 )
    {
        std::cin.clear(); 
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}
if( !IsOK ) 
    return -1;
else
    std::cin >> AnyKey;
return 0;
}

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129324

There are a few different approaches to "reading user input".

Which one works best, depends a little on the format/style of input. You can consider two different formats, "Linebased" and "free form". Free form would be input like C source code where you can add newlines, spaces, etc wherever you like.

Linebased has a set format, where each line contains a given set of inputs [not necessarily the same number of inputs, but the end of line terminates that particular input].

In a free-form input, you would have to read a character, then determine "what the meaning of this particular part is", and then decide what to do. Sometimes you also need to use the peek() function to check what the next character is, and then determine what to do based on that.

In a line-based input, you use getline() to read a line of text, and then split that into whatever format you need, for example using stringstream.

Next you have to decide whether you write your own code (or use some basic standard translation code) or use stream functions to parse for example numbers. Writing some more code will get you better ways to handle errors such as "1234aqj" isn't a number, but stream would simply stop reading when it reaches 'a' in that string.

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126432

If you take proper care that the ignoreChar will contain a digit, you can easily convert it into an integer this way:

rows = ignoreChar - '0';

The std::isdigit() function can be used to check whether a certain character represents a digit.

You can take the following sample program as an inspiration:

#include <iostream>

using namespace std;

int main()
{
    int i = -1; // Equivalent of your "rows"

    char c; // Equivalent of your "ignoreChar"
    cin >> c;

    if (std::isdigit(c))
    {
        i = c - '0';
    }
    else
    {
        // Whatever...
    }

    cout << i;
}

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

To convert a char that you know is one of '0' to '9' to an int of that numeric value, you can simply do:

rows = ignoreChar - '0';

This works because the numeric characters are guaranteed to have consecutive values by the standard.

If you need to determine whether the char is a digit or not, you can either use std::isdigit(ignoreChar) or a simple condition of ignoreChar >= '0' && ignoreChar <= '9'.

Upvotes: 0

Tony
Tony

Reputation: 848

If they are entering only one character you should be able to type cast it.

int a = (int) whateverNameOfChar;

This will convert it to it's ASCII number though so you'll have to subtract '0'

Upvotes: 0

Related Questions