cannot convert from std::basic_string to int Visual studio C++ - c++

I've written a small sudoku program and I want to make it so each time you press a certain button the text on that button is the previous number incremented by one.
So, for instance, I have a large button that says "1" and I click on it, it will say "2" then "3" if I click it again, and so on until "9".
At first I thought it would be pretty simple, I used this code to call an integer that counts to 9, a string that equals the button text and then I tried to convert int to string and I failed, it gave me the error bellow. This is the code:
int s = 0;
String^ mystr = a0->Text;
std::stringstream out;
out << s;
s = out.str(); //this is the error apparently.
s++;
And this is the error:
error C2440: '=' : cannot convert from 'std::basic_string<_Elem,_Traits,_Ax>' to 'int'
I tried searching on MSDN for that error but it's different than mine, and I left the page more confused than when I entered it.
Also for reference, I'm using a Windows Forms Application, in Windows XP, in Visual Studio 2010 C++.

If you want to convert std::string or char* to int by using std::stringstream, it could look like this:
int s = 0;
std::string myStr("7");
std::stringstream out;
out << myStr;
out >> s;
or you can construct this stringstream directly by using myStr which yields same result:
std::stringstream out(myStr);
out >> s;
And if you want to convert System::String^ to std::string, it could look like this:
#include <msclr\marshal_cppstd.h>
...
System::String^ clrString = "7";
std::string myStr = msclr::interop::marshal_as<std::string>(clrString);
although as Ben Voigt has pointed out: when you start with System::String^, you should convert it by using some function from .NET Framework instead. It could also look like this:
System::String^ clrString = "7";
int i = System::Int32::Parse(clrString);

Since you're starting with String^, you want something like:
int i;
if (System::Int32::TryParse(a0->Text, i)) {
++i;
a0->Text = i.ToString();
}

There are a lot of ways to convert a string to an int in C++ --the modern idiom may be to install the boost libraries and use boost::lexical_cast.
However, your question indicates you don't have a very good grasp of C++. If the point of your effort is to learn more about C++, you might want to try one of the many simpler tutorials before you try something as complicated as a sudoku.
If you just want to build a sudoku with Windows forms, I'd recommend you drop C++ and look at C# or VB.Net, which have many fewer pitfalls for an inexperienced programmer.

s is of type int. str() returns a string. You can't assign a string to an int. Use a different variable to store the string.
Here's some possible code (albeit it won't compile)
string text = GetButtonText(); //get button text
stringstream ss (text); //create stringstream based on that
int s;
ss >> s; //format string as int and store into s
++s; //increment
ss << s; //store back into stringstream
text = ss.str(); //get string of that
SetButtonText (text); //set button text to the string

Related

c++ if(cin>>input) doesn't work properly in while loop

I'm new to c++ and I'm trying to solve the exercise 6 from chapter 4 out of Bjarne Stroustrups book "Programming Principles and Practise Using C++ and don't understand why my code doesn't work.
The exercise:
Make a vector holding the ten string values "zero", "one", ...,
"nine". Use that in a program that converts a digit to its
corresponding spelled-out value: e.g., the input 7 gives the output
seven. Have the same program, using the same input loop, convert
spelled-out numbers into their digit form; e.g., the input seven gives
the output 7.
My loop only executes one time for a string and one time for an int, the loop seems to continue but it doesn't matter which input I'm giving, it doesn't do what it's supposed to do.
One time it worked for multiple int inputs, but only every second time. It's really weird and I don't know how to solve this in a different way.
It would be awesome if someone could help me out.
(I'm also not a native speaker, so sorry, if there are some mistakes)
The library in this code is a library provided with the book, to make the beginning easier for us noobies I guess.
#include "std_lib_facilities.h"
int main()
{
vector<string>s = {"zero","one","two","three","four","five","six","seven","eight","nine"};
string input_string;
int input_int;
while(true)
{
if(cin>>input_string)
{
for(int i = 0; i<s.size(); i++)
{
if(input_string == s[i])
{
cout<<input_string<<" = "<<i<<"\n";
}
}
}
if(cin>>input_int)
{
cout<<input_int<<" = "<<s[input_int]<<"\n";
}
}
return 0;
}
When you (successfully) read input from std::cin, the input is extracted from the buffer. The input in the buffer is removed and can not be read again.
And when you first read as a string, that will read any possible integer input as a string as well.
There are two ways of solving this:
Attempt to read as int first. And if that fails clear the errors and read as a string.
Read as a string, and try to convert to an int. If the conversion fails you have a string.
if(cin >> input) doesn't work properly in while loop?
A possible implementation of the input of your program would look something like:
std::string sentinel = "|";
std::string input;
// read whole line, then check if exit command
while (getline(std::cin, input) && input != sentinel)
{
// use string stream to check whether input digit or string
std::stringstream ss(input);
// if string, convert to digit
// else if digit, convert to string
// else clause containing a check for invalid input
}
To discriminate between int and string value you could use peek(), for example.
Preferably the last two actions of conversion (between int and string) are done by separate functions.
Assuming the inclusion of the headers:
#include <iostream>
#include <sstream>

C++, best way to change a string at a particular index

I want to change a C++ string at a particular index like this:
string s = "abc";
s[1] = 'a';
Is the following code valid? Is this an acceptable way to do this?
I didn't find any reference which says it is valid:
http://www.cplusplus.com/reference/string/string/
Which says that through "overloaded [] operator in string" we can perform the write operation.
Assigning a character to an std::string at an index will produce the correct result, for example:
#include <iostream>
int main() {
std::string s = "abc";
s[1] = 'a';
std::cout << s;
}
For those of you below doubting my IDE/library setup, see jdoodle demo: http://jdoodle.com/ia/ljR, and screenshot: https://imgur.com/f21rA5R
Which prints aac. The drawback is you risk accidentally writing to un-assigned memory if string s is blankstring or you write too far. C++ will gladly write off the end of the string, and that causes undefined behavior.
A safer way to do this would be to use string::replace: http://cplusplus.com/reference/string/string/replace
For example
#include <iostream>
int main() {
std::string s = "What kind of king do you think you'll be?";
std::string s2 = "A good king?";
// pos len str_repl
s.replace(40, 1, s2);
std::cout << s;
//prints: What kind of king do you think you'll beA good king?
}
The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there's no undefined behavior.
Yes. The website you link has a page about it. You can also use at function, which performs bounds checking.
http://www.cplusplus.com/reference/string/string/operator%5B%5D/
Yes the code you have written is valid. You can also try:
string num;
cin>>num;
num.at(1)='a';
cout<<num;
**Input**:asdf
**Output**:aadf
the std::replace can also be used to replace the charecter. Here is the reference link http://www.cplusplus.com/reference/string/string/replace/
Hope this helps.
You could use substring to achieve this
string s = "abc";
string new_s = s.substr(0,1) + "a" + s.substr(2);
cout << new_s;
//you can now use new_s as the variable to use with "aac"

How do I insert a variable result into a string in C++

I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSString stringWithFormatting:#"Hello, %#", [nameField stringValue]];
[nameField setStringValue:name];
How would I go about doing something like this with C++? Thanks for the help
I assume we're talking about Qt's QString class here. In this case, you can use the arg method:
int i; // current file's number
long total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
See the QString documentation for more details about the many overloads of the arg method.
You donĀ“t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;
That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;
std::string text = stream.str();
Qt probably has its own string types, which should work in a similar fashion.
I would use a stringstream but I'm not 100% sure how that fits into your NSString case...
stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;
I think QString has some nifty helpers that might do the same thing...
QString hello("hello ");
QString message = hello % nameField;
You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer).
You might be interested in seeing information about the difference between QString::sprintf and QString::arg.

C++ external file read: I know how to find and read a string, findMe. But how do I deal with findMei (finding any number, i, of the string)?

Apologies in advance, because I suspect this may be a silly question.
I have written a function for reading in data from an external file. I then use the data to perform calculations using other code I have written.
The function works by finding a data label that looks like this:
const std::string findMe = "<dataLabel>";
Each time I want to find data, I replace dataLabel with the label of whichever data I need from the file.
Here's what I want to do.
I don't want to have to write in the label of the data I want each time. I want to be able to do this:
for (int i = 0; i < anyNumberOfDataSets; i++)
{
findMe = "<dataLabeli>";
// Then run function for reading in data, put data into a vector.
}
I could then add any number of data sets to my external file, give each one the title
, and have each data set read into a vector.
The problem is, I simply can't figure out how to write findMe = "<dataLabeli>". Is this even possible?
I have tried things like, findMe = "<dataLabel" << i <<, but no luck!
Any suggestions would be much appreciated.
It is very hard to understand what you mean, but I guess you want this
#include <sstream>
#include <string>
for (int i = 0; i < anyNumberOfDataSets; i++)
{
std::ostringstream strm;
strm << "<dataLabel" << i << ">";
const std::string findMe = strm.str();
//...
//proceed with searching findMe
}
You can read more about string streams, for instance, here
you've already got the right answer, so this is just trying to help you with solving such problems in the future:
Your core problem here is to convert the integer i into a string s (if you've done this, than you just do findMe = "<datalabel"; findMe += s; findMe += ">";.
Googling for c++ convert integer into string will give you this as the first result. Problem solved.
This is not saying "use google before/instead of asking", it's rather "try to identify the core problem".
Another solution:
using namespace boost;
findMe = str(format("<dataLabel%d>") % i);
This will substitute %d with the value of i, formatted like printf() does.

Convert string to int and get the number of characters consumed in C++ with stringstream

I am new to C++ (coming from a C# background) and am trying to learn how to convert a string to an int.
I got it working by using a stringstream and outputting it into a double, like so:
const char* inputIndex = "5+2";
double number = 0;
stringstream ss(inputIndex);
ss >> number;
// number = 5
This works great. The problem I'm having is that the strings I'm parsing start with a number, but may have other, not digit characters after the digits (e.g. "5+2", "9-(3+2)", etc). The stringstream parses the digits at the beginning and stops when it encounters a non-digit, like I need it to.
The problem comes when I want to know how many characters were used to parse into the number. For example, if I parse 25+2, I want to know that two characters were used to parse 25, so that I can advance the string pointer.
So far, I got it working by clearing the stringstream, inputting the parsed number back into it, and reading the length of the resulting string:
ss.str("");
ss << number;
inputIndex += ss.str().length();
While this does work, it seems really hacky to me (though that might just be because I'm coming from something like C#), and I have a feeling that might cause a memory leak because the str() creates a copy of the string.
Is there any other way to do this, or should I stick with what I have?
Thanks.
You can use std::stringstream::tellg() to find out the current get position in the input stream. Store this value in a variable before you extract from the stream. Then get the position again after you extract from the stream. The difference between these two values is the number of characters extracted.
double x = 3435;
std::stringstream ss;
ss << x;
double y;
std::streampos pos = ss.tellg();
ss >> y;
std::cout << (ss.tellg() - pos) << " characters extracted" << std::endl;
The solution above using tellg() will fail on modern compilers (such as gcc-4.6).
The reason for this is that tellg() really shows the position of the cursor, which is now out of scope. See eg "file stream tellg/tellp and gcc-4.6 is this a bug?"
Therefore you need to also test for eof() (meaning the entire input was consumed).