2012-10-21 24 views
2

我需要幫助測試換行符。在我的節目,我有換行符測試

char s[9][9]; 
for(unsigned int i = 0; i < 9; i++) 
{ 
    for(unsigned int j = 0; j < 9; j++) 
    { 
     cin >> s[i][j]; 
     if(s[i][j] == '\n') 
     { 
     cout << "ERROR" << endl; 
     } 
    } 
} 

我怎樣才能得到它,這樣如果有一個換行符2-d字符數組可以檢測?我的程序似乎只是跳過if語句。如果可能,我寧願不使用getline或任何其他任何東西。

回答

3

您可以使用noskipws標誌

cin >> noskipws >> s[i][j]; 

cin.get();方法:

s[i][j] = cin.get(); 
+0

oo thanks!如果我想說如果s [i] [j]> 81個字符怎麼辦?我將如何打印第82個字符? – user1567909

+0

@ user1567909您的循環迭代9x9次。 AFAIK:9x9 == 81;)你無法達到82元素。 – PiotrNycz

0

該做的伎倆。

#include "iostream" 
using namespace std; 

int main() 
{ 
    int count = 0; 
    char s[9][9]; 
    for(unsigned int i = 0; i < 9; i++) 
    { 
     for(unsigned int j = 0; j < 9; j++) 
     { 
     cin >> noskipws >>s[i][j]; 
     count++; 
      if(s[i][j] == '\n' || count == 82) 
      { 
      cout << "ERROR" << endl; 
      } 
     } 
    } 
} 
+0

啊謝謝!如果我想說如果s [i] [j]大於82個字符,該怎麼辦?我將如何打印出第82個字符的錯誤? – user1567909

+0

使用計數器編輯以顯示一種可能的解決方案。 – DaveyLaser

+0

如果我想打印出第82個字符怎麼辦? – user1567909