Omnimaga
General Discussion => Technology and Development => Computer Programming => Topic started by: Munchor on March 16, 2011, 05:28:27 pm
-
http://pastebin.com/Ku8EWBXN (http://pastebin.com/Ku8EWBXN)
I have that code and for some reason it is crashing when running, there is no output, it crashes right after executing.
What do you think about it?
-
this should probably work.
http://pastebin.com/xpzM8rri
-
That crashed Ashbad, and so did this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string helloW = "Hello World";
int i=helloW.length();
i=i-1;
for (i;i>=0;i--)
{
if (i<helloW.length())
{
printf("%s",helloW[i-1]);
}
}
cout << helloW.length() << "/n";
cout << helloW << "/n";
cin.get();
return 0;
}
-
well obviously this shows that I'm a nub in C++ and unfortunately can't help you :( hope someone else can, though. Good luck with finding out where you went wrong!
-
well obviously this shows that I'm a nub in C++ and unfortunately can't help you :( hope someone else can, though. Good luck with finding out where you went wrong!
I'm sure you're pretty good, but thanks anyways!
-
The printf is not defined in the above sample. You should use cout instead.
-
cout is standard is C++ courses; printf is standard in C. You shouldn't mix the two if you can help it. C++ streams support output settings to accomplish the output formatting C's printf function supports.
-
So, there are 2 ways of doing it:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
string helloW = "Hello World";
int i=helloW.length();
i=i-1;
for (i;i>=0;i--)
{
if (i<helloW.length())
{
printf("%s",helloW[i]);
}
}
cout << helloW.length() << "/n";
cout << helloW << "/n";
cin.get();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string helloW = "Hello World";
int i=helloW.length();
i=i-1;
for (i;i>=0;i--)
{
if (i<helloW.length())
{
cout << helloW[i];
}
}
cout << helloW << "\n";
cin.get();
return 0;
}
Note: That was not the problem, the problem was the 'i' and 'i-1' but telling me that actually made me realise what the error in this piece of code was.
EDIT:
Here is the final code to invert a string input by the user:
#include <iostream>
#include <string>
using namespace std;
int main() {
string input = "";
string finalString = "";
getline(cin, input);
int i=input.length();
i=i-1;
for (i;i>=0;i--)
{
if (i<input.length())
{
finalString+=input[i];
}
}
cout << finalString;
cin.get();
return 0;
}
-------------------------------------
I know want to know how to slow down a C++ loop.