私の本には、整数にコンマを入力してプログラムを台無しにする人々についての通過コメントがありましたが、それは詳しく説明していませんでした。それで考えさせられたので、std :: stringを取得して、すべての非整数文字を削除する小さなアルゴリズムを書いてみました。このコードはコンパイルされますが、出力をスキップします。newstringに何も割り当てられていないのはなぜですか?if(isdigit(fstring [i]))は、数字を保持するために指しているアドレスについてtrueと評価されますか?
//little algorithm to take the non-integers out of a string
//no idea on efficiency
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter a number with non-integer characters: ";
std::string fstring;
getline(std::cin, fstring);
std::string newstring;
int i = 0, x = 0;
while (i != fstring.length())
{
if (isdigit(fstring[i]))
{
newstring[x] = fstring[i];
i++;
x++;
}
else
{
i++;
}
}
std::cout << std::endl;
std::cout << newstring;
system("PAUSE");
}
二次的な質問、それはおそらく他の場所に属します:文字列をint(または浮動小数点数)にどのように変換しますか?