2017-06-01 29 views
-1

我想读取一行字符,但只输出第二个和第四个字符。我无法忽视第一个字符。我必须使用get,peek和ignore函数。这是我的代码!不忽略C++中的第一个字符

#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; 
} 
+0

所以,如果我输入〜12/.derg它输出〜1/ – Mark

+0

你的代码甚至不试图做你所描述的。你期望第一个cin.get(char2)做什么?你认为打印char2后会做什么?这里是关于istrream的参考(http://www.cplusplus.com/reference/istream/istream/get/)我建议你阅读函数和它们做什么,然后再试一次。 –

回答

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; 
} 
0

我会做的方式是用一个字符数组...

#include <iostream> 

using namespace std; 

int main(){ 

char characterArray[4]; 
cout << "please enter four characters: "; 
cin >> characterArray; 
cout << characterArray[1] << " " << characterArray[3]; 

return 0; 
} 
0

使用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"; 
     } 
    } 
}