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.";
Related
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(), ' ');
I have a string with 6 Integer numbers inside of it '''string myStr = "1 2 3 4 5 6"'''
I want to use a stringstream to read all of those numbers individually and add them all up to find the sum.
This is part of a homework problem, just to clarify, and I need to use stringstreams as a way to read the string and add up all the numbers inside.
Here is the prompt:
"Create a string with a series of six numbers. With the help of a stringstream, add all numbers in the string"
Note:
Sorry if this is a badly structured question. any criticism of how I could make this more clear is appreciated.
I have searched for a way to do this but I am having trouble understanding just exactly how this works.
I know you need to use '''ostringstream''' or '''istringstream''' to do whatever it is I am trying to do. But I do not know HOW to use them.
I do have a coursebook "Murach's C++ Programming" which is the book we have for reference in class. But it does not go over anything about stringstreams in any other context besides reading from text files.
void stringstreams(string myStr = "1 2 3 4 5 6"){
stringstream strStream;
strStream << myStr;
myStr = strStream.str();
cout << myStr << endl;
}
Describe results:
I think all this does is send the string into a stringstream, and then send it right back the other way (I may be completely wrong about that). I am not exactly sure what to do because I don't have ANY experience whatsoever working with stringstream.
Here is another way to use the std::stringstream, without having to manually convert the string to an integer:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
std::string myStr = "1 2 3 4 5 6";
std::stringstream strm(myStr);
int value;
int sum = 0;
while (strm >> value)
sum += value;
std::cout << sum << "\n";
}
See if this simple commented code helps:
int main() {
std::string myStr = "1 2 3 4 5 6";
std::stringstream ss{ myStr}; // Initialize the stringstream; use stringstream instead if you are confused with ostringstream vs istringstream
string str;
int sum = 0;
while (getline(ss, str, ' ')) { // split stringstream into tokens separated by a whitespace
sum += std::atoi(str.c_str()); // convert each string to c- equivalent before converting to integer using atoi
}
std::cout << sum << endl;
}
It's not giving me any output and I don't know why.
I have tried switching for a while loop.
cin >> input;
for (z=0; z > input.size(); z++) {
input[z]=(int)input[z];
cout << input; }
Expected result:
Input = abc
output = 979899
No Error message.
With the subscript operator [] you can only access one element from the string and you need to write more than one digit to the string ('A' -> "97"). To do that you need to convert the char value to a literal with std::to_string().
The simples solution is to use a second string as output, then you don't get in trouble with the indexing of the input string when you need to resize the string.
std::string str = "abc";
std::string out;
for(auto a : str )
{
out.append(std::to_string((unsigned int)a));
}
std::cout << out << std::endl;
I was wondering how I could convert an int to a string and then add it to an existin string. i.e.
std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s
I hope I'm making sense. Thank you very much in advance for any answer.
If the number you want to append is an integer or floating point variable, then use std::to_string and simply "add" it:
int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << '\n';
Should output
foo123
The "modern" way is to use std::to_string(1). In fact, various overloads of std::to_string exist for different number types.
Putting this together you can write std::string s = "Hello" + std::to_string(1);
Alternatively you can use std::stringstream which can be faster due to fewer string concatenation operations which can be expensive:
std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string
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 */