c++ istringstream() function converting string to int raises error - c++

I have a string of digits. I am trying to print it as an int type each single digit in the string using istringstream. It works fine if pass whole string as argument to conversion function in main but if I pass it by index, it raises error.
How to make this code work using index to print each single digit in string array as an int.
Here is my code.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int strToNum(string str)
{
istringstream ss(str);
int n;
ss>>n;
cout<<n;
}
int main()
{
string str = "123";
for(int i=0; i<str.length(); i++)
//strToNum(str); Works fine
strToNum(str[i]); //raises error
}

str[i] is a char, while the strToNum expects a string, hence the type error.

It raises error because str[i] is a char
however , strToNum(string str) excepts a string
Try this :
for(int i=0; i<str.length(); i++)
strToNum(string(1,str[i])); //Convert char to string
See here

Others have explained your error. This is how you could make it work:
strToNum( std::string(1, str[i]) );
But I'd do this instead:
for(int i=0; i<str.length(); i++)
cout << str[i] - '0';
But ask yourself if you really need this. Are you interested in the value or the representation? If the latter, just print chars.

You don't need istringstream at all.
int strToNum(char ch)
{
cout << ch;
}

Actually I use a template function to perform this task, which is a more useful way to write the function that originated this thread ( because this single function can convert a string to any type of number: int, float, double, long double ):
#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <iomanip>
using namespace std;
template <typename T>
inline bool StrToNum(const std::string& sString, T &tX)
{
std::istringstream iStream(sString);
return (iStream >> tX) ? true : false;
}
void main()
{
string a="1.23456789";
double b;
bool done = StrToNum(a,b);
cout << a << endl;
cout << setprecision(10) << b << endl;
system ("pause");
}
setprecision(10) ( iomanip ) is required otherwise istringstream will hide some decimals

Related

ERROR: Invalid conversion from ‘const char*’ to ‘char*’ debugging homework problem

I'm new to C++ and am having a hard time debugging this. Any idea why I am getting this error? The upper function is supposed to take in a pointer to a C-string as an argument, iterate through each character in the string and convert it to uppercase. Also, how can I get my function to return the string in uppercase?
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
string upper(char* some_string){
for (int i=0; i < strlen(some_string); ++i){
toupper(some_string[i]);
cout << some_string[i];
}
return "Done"
}
int main(){
std::string word;
cout << "Enter a string: ";
cin >> word;
upper(word.c_str());
}
Make the argument const char* because the function doesn't modify the string.
Apply toupper() to what should be printed. (toupper() returns int, so the result should be casted to char to have it be printed as characters)
Add a semicolon after return "Done".
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
string upper(const char* some_string){ // use const char*
for (int i=0; i < strlen(some_string); ++i){
cout << static_cast<char>(toupper(some_string[i])); // apply toupper() to what to print
}
return "Done"; // add a semicolon
}
int main(){
std::string word;
cout << "Enter a string: ";
cin >> word;
upper(word.c_str());
}

Can we use vector in c++ to take user input of unknown size only till we hit enter?

I was trying to take user input in a vector in c++, as vector is a dynamic data structure i wanted it to take input as long as user wants and when the user hit enter key it should stop taking the input (just as a string) only difference i want to do it in an integer vector, but i am unable to do so let me know if it is possible or not to take user input in a vector like the way i described.
I have searched the web for various ways but still my code isn't running the way i want, I have tried breaking the loop of input by using EOF symbols but it is not stopping the loop of input.
I have tried using cin.ignore() function but it also takes spacebar in count
i only want to stop input when enter key is pressed.
below is the most recent code i made:
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> v;
char c;
for(int i=0;;i++){
cin>>c;
if(c=='\n'){
break;
}
int x = c - '0';// typecasting char into integer.
v.push_back(x);
}
cout<<v.size()<<endl;// just to check if it is done taking input and what is the size of vector now.
}
You can use std::getline() to get the entire line and then std::istreamstream to get the integers into a vector:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
int main() {
std::string input;
std::getline( std::cin, input );
std::istringstream is( input );
std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );
std::cout << v.size() << "\n";
return 0;
}
Read the entire line as string and build each number. Something like that:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string s; getline(cin, s);
int num = 0;
vector<int> v;
for(int i = 0; i < s.size(); ++i)
if(s[i] == ' ')
v.push_back(num), num = 0;
else
num = num*10 + (s[i]-'0');
v.push_back(num);
cout << v.size() << endl;
return 0;
}
You just have to input Vector elements as a single string and use Stringstream function to assign elements in increasing order of vector's indices respectively.
Here's the code :
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
string buffer;
int data;
getline(cin,buffer);
istringstream iss(buffer);
while(iss>>data){
v.push_back(data);
}
cout<<v.size()<<" ";
cout<<"Vector Elements"<<endl;
for(int k=0;k<v.size();k++){
cout<<v[k]<<" ";
}
return 0;
}
When you read from std::cin, it will accept an entire line from the console. Your cin>>c will retrieve the first character of the line and put that character into the variable c.
This means your if(c=='\n') is pretty much pointless since the line will be consumed and you won't see an explicit '\n' as the first character...EVER.
c - '0' will convert a single ASCII character that is a digit (i.e. 0123456789) to a number you can use, but that is NOT typecasting a char into an integer. That's converting an ASCII character that happens to be a number into a numeric value. A type cast is when you change the TYPE of a value to another TYPE.
I think you want to do something like the following...
#include <iostream>
#include <vector>
#include <stdio.h>
#include <conio.h>
int main( int cArguments, const char** apszArguments ) {
std::vector<char> vchars;
char c;
do {
c = getche();
vchars.push_back( c );
} while( c != '\n' );
std::cout << vchars.size() << " characters received" << std::endl;
return 0;
}
Note that on macOS and some Linux variants, getch/getche are not defined and you'll need to use termios or ncurses functions instead.

How to convert string of characters to their respective int values?

I'm trying to convert a string of characters into their ASCII int values. However I cannot get this to work for one even one character in the string. I would expect a result of 72 when entering 'H', but it returns a 0 (the same for every character I've tried).
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string a;
cin >> a;
const char * b = a.c_str();
int c = atoi(b);
cout << int(c) << endl;
}
Thanks in advance.
atoi parses the C-string interpreting its content as an integral number, i.e.
int i = atoi("123"); // i = 123
You don't want this: you want to know the ASCII value of every single character of the input string. To figure this out, you can use this code snippet:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
cin >> a;
for(int c: a)
cout << c << '\n';
}
I'm not quite used to the string library but simply type:
cout<<(int)a[pozition];
You can place that in a for like this.
for(int i=0;i<a.length();i++)
cout<<(int)a[i]<<endl;
You can just cast each character to an int
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
cin >> a;
for (int i = 0; i < a.length(); i++) {
cout << (int) a[i] << endl;
}
}

How to Convert a C++ String to Uppercase

I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}

stringstream: Why isn't this code returning 4?

#include <iostream>
#include <sstream>
using namespace std;
int get_4()
{
char c = '4';
stringstream s(ios::in);
s << c;
int i;
s >> i;
return i;
}
int main()
{
cout << get_4() << endl;
}
The conversion is not working for me. If I write a character '4' or character array {'4','\0'} to stringstream and then read it out to int i, I don't get back the 4. What is wrong with the above code?
Because you set the stringstream to input-only -- no output.
If you check the fail() bit after trying to extract the int, you'll see it didn't work:
s >> i;
bool b = s.fail();
if( b )
cerr << "WHOA DOGGIE! WE BLOWED UP\n";
In your code, change:
stringstream s(ios::in);
to:
stringstream s;