cin >> *integerVar >> *charVar; can read input like "25 b" correctly. What is the easiest way to do this with an existing string (I can do it manually by splitting and then parsing each part but what is the better way)?
4 Answers
Use an istringstream like, for example:
#include <string>
#include <sstream>
int main(void)
{
std::istringstream ss("25 b");
int x; std::string bstr;
ss >> x >> bstr;
return 0;
}
// note that std:istringstream allows ss >> x, but not ss << "some value".
// if you want to support both reading and writing, use a stringstream (which would then support ss >> x as well as ss << "some value")
3 Comments
HolyBlackCat
Shouldn't we use
istringstream as a more specialized class?Jon Purdy
@HolyBlackCat: I think
istringstream better expresses the intent if you only want to read, but stringstream will also work.Stephan Lechner
@HolyBlackCat: yes, that would be better; corrected the answer; thanks for the comment.
You can utilize the stringstream and string (template) classes:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string s;
std::getline(std::cin, s);
std::stringstream ss(s);
int n;
char c;
ss >> n >> c;
return 0;
}
Comments
You can use sscanf which does the exact same thing as scanf but uses a string instead of STD input
#include<iostream>
#include<stdlib>
#include<stdio>
int main(){
std::string str;
char character;
int intnumber;
cin >> str;
sscanf (str.c_str(), "%d%c", &intnumber, &character);
}
5 Comments
user4581301
Better give an example because this requires a bit of massaging of a
string to work and scanf and friends are notoriously blind when it comes to being fed the wrong data types.ZioCain
@user4581301 something like this ok?
user4581301
Pretty close. Recommend using a
std::string in place of char * for str, char instead of char * for character, and sscanf (str.c_str(), "%d%c", &intnumber, &character); on the call. because otherwise you are using some uninitialized pointers ( and an extra level of addressing on the call).ZioCain
Right, I was actually trying to use the most basic c as possible. Thank you for your comments, tho
user4581301
No worries, but note that this is a C++ question, not a C question.
stringstream will catch all (or most) of the errors you can make with sscanf at compile time. sscanf will probably compile and do something weird when run, so its use is not recommended.
std::stringstream parser("My source string");now you can useparserexactly the same way you usecin. Documentation: en.cppreference.com/w/cpp/io/basic_stringstreamnewfor every variable or instance.