【问题标题】:Reading int As Separate Digits将 int 读取为单独的数字
【发布时间】:2014-03-24 20:45:57
【问题描述】:

我在一个文本文件中有一些负数,都包含小数,我已经设法读取它们并将它们转换为整数来显示;

    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”“。”等等。这样做的原因是因为这个数字要用莫尔斯电码来表示,它已经设置在一个数组中,所以我需要单独的数字来将每个数字分配给它指定的莫尔斯电码。

【问题讨论】:

  • 为什么不使用字符串的[] 运算符循环/迭代字符串的每个单独字符?
  • 您是否期望这些数字格式不寻常?比如10E+3?
  • @R Sahu 不,应该是整数

标签: c++ arrays string loops int


【解决方案1】:

根据您发布的内容,我不会为任何本地数字转换而烦恼。我只需读取文本文件并单独遍历每个字符,将其映射到您的莫尔斯电码映射数组。如果您需要使用给定数字作为映射数组的索引,您可以通过从中“减去”“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];
}

【讨论】:

  • 这段代码给了我我需要的想法,明白了!很好的答案谢谢
猜你喜欢
  • 2011-07-08
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多