Printing first 3 digits
....
Last edited on
why not use string's ?
1 2 3 4 5 6 7 8 9 10 11
|
#include <string>
...
string input = "";
cin >> input;
if ( input.length() >= 3 )
cout << input.substr (0, 3);
else
cout <<"String too short";
|
Last edited on
I know how to do it with strings. I want it in a form of a while loop because I know it's possible.
While the number is more than 3 digits, divide it by 10 - integer division means the right-most digit will just get chopped off.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <string>
#include <iostream>
using namespace std;
int main() {
string input = "";
cin >> input;
if (input.length() >= 3)
cout << input.substr(0, 3) << endl;
else
cout << "String too short" << endl;
int i = 0;
cin >> i;
int j[10] = { 0 };
int k = 0;
while ( i > 0 )
{
j[k] = i % 10;
i = i / 10;
k++;
}
cout << j[k-1] << j[k-2] << j[k-3] << endl;
return 0;
}
|
I just figured out how to print the first number using this method. Now, I'm trying to figure out how to print the subsequent two numbers. Any takers?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
using namespace std;
int main () {
int x;
cout << "Enter an integer: ";
cin >> x;
while(x > 10) {
x = x / 10; // first digit
}
cout << x;
}
|
Enter an integer: 7689
7
Last edited on
Try line 15 onwards above
while(x > 10)
should be
while(x >= 1000)
Topic archived. No new replies allowed.