Reputation: 15
I am new to programming, started with C++ quite recently and I use CLion IDE.
I need to solve something, but I am not sure how exactly and I need your help with a basic C++ console program.
if the user enters a ten-digit number and the fifth number is one, the output should be this word - "zadochno".
if the user enters a ten-digit number and the fifth number is two, the output should be this word - "redovno".
The user is expected to enter 2101162235 or similar. In any case, the fifth element should be either 1 or 2.
Examples:
Option 1: input> 2101162235 -> output string "zadochno"
Option 2: input> 2101262235 -> output string "redovno"
I am able to only partially create the program:
#include<iostream>
int number;
cout << "Please, enter number: ";
cin > number;
//I believe there should be an if statement or for loop here:
if(){
}
Can you please help me?
Upvotes: 0
Views: 1019
Reputation: 1
You can take the input from the user as std::string
and then check if the element at index 4
is 1
or 2
as shown below:
#include <iostream>
#include <string>
int main()
{
std::string input;
//take input from user
std::getline(std::cin, input);
//check if the 5th letter(at index 4 since indexing starts with 0) is '1' or '2'
if(input.at(4) == '1')
{
std::cout<< "zadochno"<<std::endl;
}
else if(input.at(4) == '2')
{
std::cout << "redovno"<<std::endl;
}
//this below shown for loop is optional. If you're sure that the user input contains only digits then you can skip/remove this for loop.
for(int i = 0; i < input.size(); ++i)
{
//check if the all the characters are digits of a number
if(std::isdigit(input[i]))
{
;//std::cout<<"yes digit";
}
else
{
std::cout<<"Please enter a valid number"<<std::endl;
}
}
return 0;
}
The output of the above program can be seen here.
Upvotes: 1
Reputation: 123431
Assuming the user does enter a 10 digit number (ie you don't need to check if they enter eg "foo"
or "bar3000"
), you can do the following:
Read the input as a std::string
, not as int
. User input is a string of characters always. Only if you need it you can get it converted to an integer. You do not need it as int
. The n-th character of a std::string
called user_input
is user_input[n]
. You just need to check whether the character in the middle is either '1'
or '2'
.
If you do need to check that the user did enter digits, you could use std::isdigit
.
Upvotes: 1