convert integer to string for function parameter [duplicate] - c++

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
How to convert a number to string and vice versa in C++
(5 answers)
Closed 10 years ago.
I have a function which accept a string parameter and I have an integer variable then I should convert it to string and then pass it to that function I used this code but as ostringstream is for I/O it doesn't work.
ostringstream ostr;
while (.....)
{
regnum++;
ostr<<regnum;
grph.addlastname(ostr.str());
}
for example it pass 12345 to function instead of 5,what should I do?

It's true - there are a lot of similar questions which solve "What's the best way to do this?" but I think that there's something to learn for the OP in the answer to the question of "Why does this not work?"
Therefore:
Your stringstream has an internal state, and during your loop you always append a new digit - but the previous ones are still in the stream! You can fix this by making the stringstream scope-local to the loop, i.e. declaring it inside the loop rather than outside of it.
(std::to_string is still the better solution for this particular problem, though.)

Everything is fine except one thing,
see:
ostringstream ostr;
while (.....)
{
regnum++;
ostr<<regnum;
grph.addlastname(ostr.str());
}
Your declaring your ostr outside the while, the first time that while runs, it adds '1' to the ostr, the second time, because it's the same "ostringstream" variable, it adds '2', so your string will be '12' now...
Solution: Declare ostringstream ostr, inside your while, use std::to_string, or do a ostr.clear() every time that the while ends. (The best way si declaring your ostr inside your while)

Related

How to make a function that takes in a std::string parameter that will return the amount of anything surrounded by whitespace [duplicate]

This question already has answers here:
Counting words in a string
(8 answers)
Closed 1 year ago.
I want to create a function that takes in a std::string parameter and returns an int of the amount of words in it. Like this:
int countWords(std::string){
// code...
return amountOfWords;
}
Write a function stub:
int stub(const std::string& s/*don't deep copy the string*/)
{
return function_you_found_online(s.c_str());
}
The function c_str() returns a const char* to the first character in s.
Using function stubs to wrap third party resources also has the advantage that you can switch out the resources at a later date without impacting your codebase too much.

C++ adding n strings to a string stream [duplicate]

This question already has answers here:
Variable number of arguments in C++?
(17 answers)
Closed 4 years ago.
I am kind of stuck in pre C++ 11 land. How can I write a function that takes n strings and appends them to an ostreamstream?
void Foo(std::string first_part, ...){
std::ostringstream oss;
oss << first_part << ...; // cant do it
for(int i = 0; i < ....length(); i++){ // :|
}
}
If I lived in a perfect world I could do the above. Is there any other way pre C++ 11 to loop through the ... arguments?
Sorry, but it can't be done directly (at least not in portable code).
Attempting to pass a non-trivial type (including std::string) as a variadic argument gives undefined behavior.
If you want to do something similar, you could (for one example) pass the addresses of a number of strings rather than attempting to pass the strings themselves.
If you do that, you'll still have to contend with one other detail: you'll need to tell the receiving function the number of (addresses of) strings to expect.
From there, the receiving function would use va_start, va_arg and va_end to retrieve the data and do it's thing with them.

C style strings [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 6 years ago.
Even though the name of the string signifies address of the first element in the string,when I perform this:
char str[]="dog";
cout<<str<<endl;
How come the whole string gets printed?
In C++, the "<<" operator is "smart". It knows the types of the thing to its left and to its right, and if the thing to its right is a character pointer and the thing to its left is an output stream, it prints the string rather than the value of the pointer.
In C, you have to tell printf() which one to do with "%p" or "%s", but "<<" makes that choice for you.
Google "C++ operator overloading"

MoveFileA() doesn't like my arguments [duplicate]

This question already has answers here:
How to convert std::string to LPCSTR?
(9 answers)
Closed 8 years ago.
I have a list of file names in a .txt document, and I would like to move each of these files from one folder to another.
Using MoveFileA() I am getting the error, "no suitable conversion between std::string and LCPSTR".
Here is my code, after opening up my .txt file:
while (std::getline(myfile, line))
{
std::string oldLocation = "C:\\Users\\name\\Desktop\\docs\\folder1\\" + line;
std::string newLocation = "C:\\Users\\name\\Desktop\\docs\\folder2\\" + line;
MoveFileA(oldLocation, newLocation);
}
If I type in the full path as arguments for MoveFileA, instead of sending it a variable, it works but I am unable to iterate over .txt file this way.
Any suggestions on how I might fix this?
LCPSTR means long constant pointer to a string, which means it's a null terminated c string.
std::string is an object. It is something different. But it luckily provides a convenience method c_str the provides a pointer to a constant c style string. So as the comment says you should go by:
MoveFileA(oldLocation.c_str(), newLocation.c_str());
It is worth of explicitly noting, that you can't drop it in every place instead of char*, but only when the string won't be modified. It returns const char*. This is where the C in LCPSTR gets important.

Char to Int in C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.
Have you tried atoi or boost lexical cast?