Split string "A10" into char 'A' and int 10 - c++

Given a string consisting of a single character followed by a number (one or two digits), I would like to split it into a character and an integer. What is the easiest way to accomplish this?
My thoughts so far:
I can easily grab the character like so:
string mystring = "A10";
char mychar = mystring[0];
The hard part seems to be grabbing the one or two digit number that follows.

#include <sstream>
char c;
int i;
std::istringstream ss("A10");
ss >> c >> i;//First reads char, then number.
//Number can have any number of digits.
//So your J1 or G7 will work either.

You can make use of the operator[], substr, c_str and atoi as:
string s = "A10";
char c = s[0]; // c is now 'A'
int n = atoi((s.substr(1,2)).c_str()); // n is now 10
EDIT:
The above will also work if s="A1". This is because if the 2nd argument to substr makes the substring to span past the end of the string content, only those characters until the end of the string are used.

Using sscanf()
std::string s = "A10";
int i;
char c;
sscanf(s.c_str(), "%c%d", &c, &i);
/* c and i now contain A and 10 */
This is more of a "C way" of doing things, but works none-the-less.
Here is a more "C++ way":
std::string s = "A10";
std::cout << *s.begin() << s.substr(1, s.size()) << std::endl;
/* prints A10 */

Related

Parse a String in C++ and connect input-arguments to existing variables

I want to read an input string and connect their values to variables in my class.
Some example Inputs might be:
78 C 15.48
3 B
87 P 15
0
..
The first argument is an int from 0-100, second a char and third int or float. A String can consist of one, two or three arguments which are separated by space. After reading a line, this program does some calculations and then expects another input until a 0 is entered or a break occurred.
To read an input String, i'm currently using
std::string str;
std::getline(std::cin, str);
My program already has the variables
int firstArgument;
char secondArgument;
float thirdFloatArgument;
int thirdIntArgument;
now, lets say str is: 46 C 87.3
after reading the line my variables should be:
firstArgument = 46;
secondArgument = 'C';
thirdFloatArgument = 87.3;
How can I extract the Information from the input String?
I was thinking about counting the spaces to see how much values are given and then separating the string via this delimiter,as the amount of arguments might vary. So:
int count = 0;
int length = str.length();
for(int i = 0; i < length; i++){
int c = str[i];
if(isspace(c)){
count++;
}
}
with space count being 2 I now know that 3 arguments were passed, but I don't know how to go on from there. Using std:istringstream might be an option but from what I've seen online it is mostly used in a while loop to print each word of a string in a new line or like that. But my input can vary in the amount of arguments so a loop would not work.
I think I need something like: "String before first ' ' is firstArgument, String between first and second ' ' is secondArgument, string after second ' ' is either thirdFloatArgument or thirdIntArgument (respectively if only one or two arguments are given, which can be determined with the amount of spaces). But how would I do this? Or are there some easier approaches?
Big thanks in advance!
As Some programmer dude mentioned it is a good idea to use std::istringstream to convert values from string to other data types. It allows you to treat input string the same way as you treat std::cin. Here is a code snippet that you can use in your case:
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
struct Arguments {
int first{};
char second{};
double third{};
};
Arguments parseArgs(const std::string& inputLine) {
Arguments args;
const int argc = std::ranges::count(inputLine, ' ');
std::istringstream stream(inputLine);
if (argc >= 0) {
stream >> args.first;
}
if (argc >= 1) {
stream >> args.second;
}
if (argc >= 2) {
stream >> args.third;
}
return args;
}
int main() {
std::string inputLine{};
std::getline(std::cin, inputLine);
const auto args = parseArgs(inputLine);
std::cout << args.first << ", " << args.second << ", " << args.third << "\n";
}
Note that you have to compile this example using C++20 because I used std::ranges. If you do not have compiler that supports this standard you can use std::count(inputLine.cbegin(), inputLine.cend(), ' ');

Count letters in String without using strlen()

I created a program that the user enters a string. But i need to count how many letters are in the string. The problem is im not allowed to use the strlen()function. So i found some methods but they use pointers but im not allowed to use that yet as we havent learned it. Whats the best way to do this in a simple method? I also tried chars but i dont have luck with that either.
#include <iostream>
using namespace std;
string long;
string short;
int main()
{
cout << "Enter long string";
cin >> long;
cout << "Enter short string";
cin >> short;
return 0;
}
I need to get the length of long and short and print it.
I am trying to use it without doing strlen as asked in some previous questions.
Do you mean something like this?
//random string given
int length = 1;
while(some_string[length - 1] != '\0')
length++;
Or if you don't want to count the \0 character:
int length = 0;
while(some_string[length] != '\0')
length++;
You can count from the beginning and see until you reach the end character \0.
std::string foo = "hello";
int length = 0;
while (foo[++length] != '\0');
std::cout << length;
If you use standard cpp string object I think the best way to get length of your string is to use method:
long.size();
It gives you number of characters in string without end string character '\0'. To use it you must include string library :
#include <string>
If you decide to use char table you can try method from cin:
char long_[20];
cout << "Enter long string\n";
int l = cin.getline(long_,20).gcount();
cout << l << endl;
gcount()

Struggling with a textcounter

I tried to write myself a textcounter which tells me how many characters and words are in a piece of text. Every time I try to paste in a long piece of text for it to count, it will crash or display something random.
Does anyone have any suggestions?
This is what I have written:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Text counter\nPlease insert text.\n";
string text = "";
getline(cin, text);
double countTotal = text.size();
cout << "Total characters: " << countTotal << "\n";
int wordCount = 1;
for (int chrSearch = 0; chrSearch < (int)text.size(); chrSearch++)
{
char chr = text.at(chrSearch);
if(chr == ' ')
{
wordCount++;
}
}
cout << "Total words: " << wordCount << "\n";
return 0;
}
First of all, the code reads at most one line: std::getline(std::cin, line) stops reading upon receiving the first newline. You can specify a character where to stop, e.g, the character '\0' is unlikely to be present in typical text. For example, you could use:
std::string text;
if (std::getline(std::cin, text, '\0')) {
// do something with the read text
}
You should also always check that input was successful. While the above would work with short texts, when the texts become large it makes more sense to read them one line at a time and eventually reading a line will fail when the end of the stream is reached.
In case you don't like the approach of reading everything up to a null character, you could read the entire stream using code like this:
std::istreambuf_iterator<char> it(std::cin), end;
std::string text(it, end);
if (!text.empty()) {
// do something with the read text
}
A few notes on the other parts of the code:
Don't use double where you mean to use an integer. You may want to use a bigger integer, e.g., unsigned long or unsigned long long but double is for floating point values.
When iterating through a sequence you should either use an unsigned integer type when dealing with indices, e.g., unsigned int or std::size_t. This way there is no need to cast the size(). Preferably you'd use iterators:
for (auto it(text.begin()), end(text.end()); it != end; ++it) {
char chr(*it);
// ...
}
or
for (char chr: text) {
// ...
}
Note that your word count is wrong if there are two consecutive spaces. Also, if you don't break your text using line breaks, you need to use '\n' as an additional whitespace character separating words. If you want to consider all spaces, you should actually use something like this to determine if a character is a space:
if (std::isspace(static_cast<unsigned char>(chr)) { ... }
The static_cast<unsigned char>(chr) is needed because char tends to be signed and using a negative value with std::isspace() results in undefined behavior. Casting the character to unsigned char avoids any problems. Note that negative characters are not entirely uncommon: for example, the second character of my last name (the u-umlaut 'ΓΌ') normally result in a negative char, e.g., when UTF-8 or ISO-Latin-1 encoding is used.

convert char to string

Hello? I want to know "how to convert char to string"
This is my C code
string firSen;
int comma1=0;
cout<<"Please write your sentence"<<endl;
getline(cin,first);
int a=firSen.first("string");
for(i=a;firSen[i] != ',';i++)
comma1=i;
cout<<firSen[comma1-3]<<firSen[comma1-2]<<firSen[comma1-1]<<endl;
I will write "The string is 100s, Thank you"
I know firSen[comma1-3]=1, firSen[comma1-2]=0, firSen[comma1-1]=0 for type of char.
And I want to put these char into string
(Like 1,0,0 into string of 100) because I want to use atoi function....
Do you know how to convert char into string?
You can use std::istringstream instead of atoi.
Something like this:
std::istringstream ss(firSen.substr(comma1-3));
int val;
ss >> val;
In this case, if you know the location and length that you want, you can just extract a substring:
std::string number(firSen, comma1-3, 3);
and convert that to an integer type using the C++11 conversion functions:
int n = std::stoi(number);
or, historically, a string stream:
int n;
std::stringstream ss(number);
ss >> n;
or, if you want to be really old-school, the C library
int n = std::atoi(number.c_str());
There are other ways of building strings. You can initialise it from a list of characters:
std::string number {char1, char2, char3};
You can append characters and other strings:
std::string hello = "Hello";
hello += ',';
hello += ' ';
hello += "world!";
or use a string stream, which can also format numbers and other types:
std::stringstream sentence;
sentence << "The string is " << 100 << ", thank you.";

string (from substr) conversion to unsigned int

I have a string which actually contains a number and a string, separated by ,, for instance "12,fooBar".
I would like to put it into separated variables, i.e. the number into unsigned int myNum and the string into std::string myStr.
I have the following snipped of code:
size_t pos1=value.find(',');
std::cout << value.substr(0, pos1) << " and "
<< (value.substr(0, pos1)).c_str() << std::endl;
This yields 12 and 1. Anything I missed here? What happend to the 2 in the second part?
Note: I isolated the problem to this snipped of code. I need c_str() to pass it to atoi to get the unsigend int. Here I don't want to print the second part.
Update: I actually get the string from levelDB Get. If I put a test string like I put here, it works.
The posted code produces the same substring: value.substr(0, pos1). Note that std::string::substr() does not modify the object, but returns a new std::string.
Example:
#include <iostream>
#include <string>
int main ()
{
std::string value ="12,fooBar";
unsigned int myNum;
std::string myStr;
const size_t pos1 = value.find(',');
if (std::string::npos != pos1)
{
myNum = atoi(value.substr(0, pos1).c_str());
myStr = value.substr(pos1 + 1);
}
std::cout << myNum << " and "
<< myStr << std::endl;
return 0;
}
Output:
12 and fooBar
EDIT:
If the unsigned int is the only piece required then the following will work:
unsigned int myNum = atoi(value.c_str());
as atoi() will stop at the first non-digit character (excluding optional leading - or +), in this case the ,.
The cleanest C++ style solution to this problem is to use a stringstream.
#include <sstream>
// ...
std::string value = "12,fooBar";
unsigned int myNum;
std::string myStr;
std::stringstream myStream(value);
myStream >> myNum;
myStream.ignore();
myStream >> myStr;
Your second substr should be value.substr(pos1+1,value.length())
One more option is using std::from_chars function from the 17th standard (< charconv > header):
int x;
from_chars(&s[i], &s.back(), x); // starting from character at index i parse
// the nearest interger till the second char pointer
There are different overloads for different types of value x (double etc.).