【问题标题】:Not ignoring first character in c++不忽略 C++ 中的第一个字符
【发布时间】:2017-06-01 02:23:09
【问题描述】:

我正在尝试读取一行字符,但只输出第二个和第四个字符。我无法忽略第一个字符。我必须使用 get、peek 和 ignore 函数。这是我的代码!

#include<iostream>
#include<iomanip>

using namespace std;

int main()
{

char char2, char4;

cout << "Enter an arbitary line. "<<endl;



cin.get(char2);
cout << char2;
cin.get(char4);
cout << char4;

cin.ignore(1, '\n');


cin.peek();
cin.get(char2);
cout << char2 << endl;


    return 0;
}

【问题讨论】:

  • 所以如果我输入 ~12/.derg 它输出 ~1/
  • 您的代码甚至没有尝试执行您所描述的操作。你期望第一个 cin.get(char2) 做什么?您认为之后打印 char2 会做什么?这是对 istrream (cplusplus.com/reference/istream/istream/get) 的参考,我建议您阅读这些函数以及它们的作用,然后再试一次。

标签: c++ getline


【解决方案1】:

模式是继续从输入流中读取,并将读取表达式放入while循环本身,就像下面的代码一样,这样循环会自动退出而无需显式检查

#include <iostream>

using namespace std;

int main() {
    auto ch = char{};
    auto counter = 0;

    while (cin.get(ch)) {
        counter++;
        if (ch == '\n') {
            counter = 0;
            continue;
        } else if (counter == 2 || counter == 4) {
            cout << ch;
        }
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    我会这样做的方式是使用字符数组...

    #include <iostream>
    
    using namespace std;
    
    int main(){
    
    char characterArray[4];
    cout << "please enter four characters: ";
    cin >> characterArray;
    cout << characterArray[1] << " " << characterArray[3];
    
    return 0;
    }
    

    【讨论】:

      【解决方案3】:

      如果可能,使用std::getline 读取一行并打印第二个和第四个字符。

      #include <iostream>
      #include <string>
      
      int main() {
          std::string line;
          if (std::getline(std::cin, line)) {
              int n = line.size();
              if (n >= 2) {
                  std::cout << line[1] << "\n";
              }
              if (n >= 4) {
                  std::cout << line[3] << "\n";
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-05
        • 2021-10-23
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多