I need help with this if statement. Im trying to read each character to see if it is a number. If it is not a digit then say it is not a number if it is continue reading on to the next character. for example if the user inputs 54gr 21 gr42 134 3f3. the only thing that would cout is 21 and 134.
#include <iostream> // libraries
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char string[80];
// char num[80];
// char good[80];
cout << "enter a string "; // prompting user
cin.getline(string,80); // geting line
// int i = 0;
// int j = 0;
int count = 0;
{
while(string[count] != '\0') {
if(string[count] >= '0' && string[count] <= '9' )
cout << count << endl;
}
++ count;
}
}
I would not try to do this character by character. The problem is that you don't now that 5 is really part of a number until you've read to the end of the string of non-space characters to verify that all the contents are legitimately part of a number.
As such, I think you need/want to break the input up into "words", then check whether each complete word can be converted entirely to a number. You can read "words" with just some_stream >> some_string;
Once you have a "word" you check whether you can convert it entirely to a number. Assuming you want integers, you use strtol to (try to) convert it to a number. That will give you a pointer to the first character it couldn't convert as a number. If that's not the end of the string, then that "word" wasn't a number (even if it started with/contained one or more digits).
Related
I am trying to write a code that will accept an integer input and then calculate the smallest number possible using digits not found in the inputted integer. The possible digits would be 0-9, however, 0 can not be the leading value in the output.
For example, if the user enters:
6789
the the program would output:
102345
How can I solve this?
The lowest number possible from any set of digits (ignoring, for now, the issue of the zero) comprises those digits in order; thus, from the digits 2, 1, 6 and 3, the lowest number is 1236.
So, we can start of with a list of all digits, in order, then run through the digits in the given input number (after we have converted that to a string), removing each of those digits from our list (if it's still in it). If we end up with a list whose first element is zero, we simply swap that with the second digit.
Here's a possible implementation:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string numbs = "0123456789";
int input;
std::cout << "Enter a number: ";
std::cin >> input;
std::string check = std::to_string(input); // Convert our input to a string
for (auto digit : check) { // Remove each digit in that from our list...
size_t p;
if ((p = numbs.find(digit)) != std::string::npos) numbs.erase(p, 1);
}
// A basic error check that at least one digit remains ...
if (numbs.length() == 0) {
std::cout << "No digit left with which to make a number!\n";
return 1;
}
// Swap first two digits if first is zero and there is at least one other ...
if (numbs[0] == '0' && numbs.length() > 1) std::swap(numbs[0], numbs[1]);
int answer = std::stoi(numbs);
std::cout << answer << std::endl;
return 0;
}
In this example, I have used the std::string container class from the Standard Library; in many ways, that acts like an array of characters; however, if you want to use actual arrays, you could readily adapt the shown code to use them.
Yet another implementation. Same algorithm as from Adrian . . .
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
// Basic string
std::string allDigits{ "0123456789" };
// Get input. Digits only
if (std::string input{}; std::getline(std::cin, input) and std::all_of(input.begin(), input.end(), std::isdigit)) {
// Erase from the allDigits string the characters that are in the input string
std::erase_if(allDigits, [&](const char d) { return std::any_of(input.begin(), input.end(), [d](const char c) { return c == d; }); });
// Take care of leading 0
if ((allDigits.length() > 1) and allDigits.front() == '0') std::swap(allDigits[0], allDigits[1]);
// Show result
std::cout << allDigits << '\n';
}
else std::cerr << "\n*** Error: Invalid input\n\n";
}
hi can someone please help me to complete this code in c++ if you may interested
here is the project which will print the position of a char in string, this is very close to my task but not exactly
here is the problem: program only print the position of a char, for example for letter 'S' it prints 18 because it sits at position 18, how i can change this program which instead of that, the program print my values, i don't really care about the position i care about the value that should return or store, the value i specify,
program for sam prints
S=18
A=1
M=13
instead i want it know for letter S print 7 or store 7, i mean instead of caring about position should care about the value at the final result which i explained
all 26 alphabet as you see has a value base on the position i want that pos value to be changed and result other pos int value
#include<iostream>
#include<string>
#include<exception>
#include <cstdlib>
#include<stdio.h>
#include <cctype>
using namespace std;
int main()
{
const std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "Please enter your the name:";
std::string text;
std::cin >> text;
// convert all lower case characters to upper case
for (char& c : text)
c = std::toupper(c);
// Lookup character
for (char& c : text) // for each character c in text
{
const auto pos = alpha.find(c);
if (pos != std::string::npos) // if found (if the character is an alpha character)
// note: non-alpha characters are ignored
{
const int value = pos + 1; // +1 because position of 'A' is 0, value of 'A' is 1
// Print the character and the position
cout << c << "=" << pos << endl;
}
}
}
It depends on what kind of result you're looking for. If you're looking to return values in the range of the alphabet, then just rearrange the letters to match what you want them to return.
If you're looking for something with higher or lower values, then take a look at building a map and accessing the key value pairs. https://en.cppreference.com/w/cpp/container/map
This exercise asks to take a input as a character array of number then add up the digits of the number.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main() {
//Input a series of single digit numbers
char numbers[] = "a";
cout << "Input a series of single digit numbers." << endl;
cin >> numbers;
//convert the character array into a int array.
int sum = 0;
for (int i = 0; i < size; i++) {
sum += atoi(numbers[i]);
}
cout << "Sum of digits: " << sum;
return 0;
}
The atoi function, by my understanding, converts only whole character arrays (C strings) at a time, and I guess I cant step through the array, but it seems like this should work. My other option was to convert the Cstring to one large integer, then use the length of the string to step through and calculate the digits in each position but that's probably more inefficient that I could be making it.
What would you use to find single digits as ints for a character array?
char numbers[] = "a";
This creates an array of 2 char items. That's not sufficient for anything reasonable. Use a std::string instead.
cin >> numbers;
Better use std::getline from the <string> header.
sum += atoi(numbers[i]);
atoi takes a string as argument, not a single char. You want the sum of the digits, not the sum of the number values you get by applying atoi to all right substrings of the specification.
For a digit character ch, the corresponding digit value is ch - '0'.
I have the code but it prints the letters in uppercase but also prints some weird characters afterwards. I just wanted to know how to just get the letters.
the program executing picture.
using namespace std;
int main()
{
const int SIZE = 81; // Constant for size of an array
const int MIN_LOWERCASE = 97; // Start of lowercase letters in ASCII
const int MAX_LOWERCASE = 122; // End of lowercase letters in ASCII
char line[SIZE]; // Initializing character line for input
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
for (int count = 0; count < SIZE; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
cout << endl;
system("pause");
return 0;
}
You need to use the actual size of the text that you read. Else you will print extra characters.
for (int count = 0; count < strlen(line); count++)
You might need #include <cstring> to use strlen().
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
int strLen=strlen(line)
for (int count = 0; count < strLen; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
Ypur loop is running 80 times no matter what is the size of string.
Actually, getline / cin / scanf etc. functions for char[] is explained following example:
The string is initialized for char c[10];. The input is "abcd".
First, c[i] is initialized unknown value, because it is local variable (If it is a global variable, you can assume that c[i] = 0)
Second, If you input, the value of c[i] only changed where 0<=i<=4 because the length of input is 4.
In this case, currently c = { 'a', 'b', 'c', 'd', '\0', ?, ?, ?, ?, ?}. (? denotes unknown value)
Third, you are looping i for 0 to size_of_array_c, so your output will be "abcd?????" (I don't know the value of ?).
So, you can fix the bug if you only loop while c[i] != '\0'.
The idiomatic way of doing this in C++ is
#include <string>
#include <locale>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::locale loc(""); //< the current system locale
std::string line; //< will contain the input line
std::cout << "Enter a string of 80 or fewer characters:\n";
std::getline(std::cin,line);
std::string lower; //< will contain the output
// This is the "key" of everything
std::transform(line.begin(),line.end(), // transform the entire input...
std::back_inserter(lower), // by writing into the back of the output string ...
[&loc](auto c){ return std::tolower(c,loc); }); // the result of std::tolower applied to all character, using the system locale
std::cout << "The transformed string is:\n" << lower << std::endl;
return 0;
}
// look ma! No pointers, array sizes, overflows and explicit memory management.
// And works consistently with the language your computer is set up.
I am trying to code a C++ program that takes a 5 character long string and then prints out the string with a new permutation with this order: 1st character, 3rd character, 5th character, 2nd character, 4th character. My code is as follows:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string key;
string p10;
cout << "Enter the five characters long string: ";
cin >> key;
p10 = key[0] + key[2] + key[4] + key[1] + key[3];
cout << p10 << endl;’
system(“pause”);
return 0;
}
The output (p10) is a random Greek letter every time I run it.
Please help!
The problem here is that when you use [] on a string, you're not getting back another string, but a single char. A char is actually just a small integer number (think character code), and if you use the + operator with them, it'll add the numbers together. You'll end up with a more or less random character code, which is why you get greek letters.
If you want to keep the structure of the code as close to the original as possible, you can use substr to get "one character strings" instead of plain chars:
key.substr(0, 1) + key.substr(2, 1) + ...
The 1 signifies that you want one character from the specified offset.
Another way is to first construct a char array out of the characters and then turn it into a string:
char p10_arr[] = { key[0], key[2], ... };
string p10(arr, sizeof(arr));
And perhaps the nicest and most concise way is to use the initializer list syntax:
string p10 { key[0], key[2], ... };