读取int作为单独的数字

时间:2014-03-24 20:45:58

标签: c++ arrays string loops int

我在文本文件中有一些否定的数字,都包含十进制,我已设法读取它们并将它们转换为整数来显示;

    for (int i = 0; i < 1; i++)
    {



        std::string str = &(cmemblock[0]); //cmemblock is the .txt file
        std::istringstream iss(str);
        std::vector<int> numbers;
        int number;
        while (iss >> number) {
            numbers.push_back(number);  // collect inputs

            cout << number << endl; //Displays Stored Value
            }





        if (!iss.eof()) {
            cout << "Blank Space"<<endl; //Error message to detect blank space
        }
    }

我需要帮助创建一个循环来读取每个字符,例如,如果第一行是'-0.009876',则每个值应该单独读取,' - ','0''。等等。这样做的原因是因为数字是用莫尔斯码表示的,莫尔斯码已经在一个数组中设置了,所以我需要用个别号码将每个数字分配给它指定的莫尔斯码。

1 个答案:

答案 0 :(得分:0)

根据您发布的内容,我不打扰任何本地数字转换。我只需读入文本文件并分别遍历每个字符,将其映射到您的莫尔斯代码映射数组。如果你需要使用给定的数字作为映射数组的索引,你可以通过从它“减去”'0'将它从char转换为int值,例如,假设使用charPosition作为最外层循环索引的循环字符串..

//...omitting other fairly obvious loop code
// with str holding '-0.009776'

if (isdigit(str[charPosition]))
{
   int index = str[charPosition] - '0';
   // index into 0-based array of presumed morse code mapping values
   morseValue = morseMap[index];
}