I'm trying to write a for loop that removes all the letters from a string. When I run it, it seems like the !isdigit function only removes a handful of letters, leaving some. Is there an easier way to do this? Thanks in advance for the help!!
#include "stdafx.h"
#include <cctype>
#include <sstream>
#include <iostream>
#include <string>
#define ISBN_X 9
#define ISBN_SIZE 10
usingnamespace std;
bool is_ISBN10_Valid(string);
int _tmain(int argc, _TCHAR* argv[])
{
string c;
int a;
string isbnNo;
cout<< "Please enter your 10 digit ISBN now: "; //here the user enters his or her input.
std::getline(std::cin, isbnNo);////here the user enters his or her input, whitespaces and all.
cout << "Length of text input: " << isbnNo.length() << endl << endl << endl; // Displayes the total number of input characters.
//Below is a for loop which should remove all the numbers from the input string.
for ( int x = 0 ; x <= isbnNo.length() ; x++)
{
if (!isdigit(isbnNo[x])) // If the input character is not a number....
isbnNo.erase(x, 1); //...then remove it from our string.
}
If you erase a character you should not do x++, because the string has closed up the gap caused by erasing the char.
Try this:
1 2 3 4 5 6 7
for ( int x = 0 ; x <= isbnNo.length() ; )
{
if (!isdigit(isbnNo[x])) // If the input character is not a number....
isbnNo.erase(x, 1); //...then remove it from our string.
else
x++;
}
#include "stdafx.h"
#include <cctype>
#include <sstream>
#include <iostream>
#include <string>
#define ISBN_X 9
#define ISBN_SIZE 10
usingnamespace std;
bool is_ISBN10_Valid(string);
int _tmain(int argc, _TCHAR* argv[])
{
string c;
int a;
string isbnNo;
cout<< "Please enter your 10 digit ISBN now: "; //here the user enters his or her input.
std::getline(std::cin, isbnNo);////here the user enters his or her input, whitespaces and all.
cout << "Length of text input: " << isbnNo.length() << endl << endl << endl; // Displayes the total number of input characters.
//Below is a for loop which should remove all the numbers from the input string.
for ( int x = 0 ; x < isbnNo.length() ; ) //*** Correction made to the loop test
{
if (!isdigit(isbnNo[x])) // If the input character is not a number....
isbnNo.erase(x, 1); //...then remove it from our string.
else
x++;
}
}