1

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;
    }
5
  • What is rows? An int? Commented Feb 12, 2013 at 16:07
  • Are you sure you are allowed to only use cstdlib? Because that looks like <istream> for me Commented Feb 12, 2013 at 16:08
  • pretend rows is already decalred before Commented Feb 12, 2013 at 16:08
  • 1
    If you are sure that ignoreChar is a digit, then rows = ignoreChar - '0'; will work Commented Feb 12, 2013 at 16:09
  • @sonicboom: btw, I understood rows is declared before. I asked what is it declared like. An int? Commented Feb 12, 2013 at 16:10

5 Answers 5

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

0

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'.

Comments

0

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.

Comments

0

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

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.