0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列(配列)を作成せず一文字ずつ処理する方法

Posted at
#include <bits/stdc++.h>
using namespace std;

int main(){
    char ch;
    cin >> ch;
    cout << ch << endl;
    return 0;
} 
//入力→ABC
//出力結果→A

char型は一文字だけ入る箱である。そのため、2つ以上の文字をchar型箱に入れる場合、初めの1文字目のみ箱に入る!(2文字目以降の文字は排除される)

#include <bits/stdc++.h>
using namespace std

int main(){
    char ch;
    while(1){
        scanf("%c",ch); 
     //cin >> chにすると、改行が読み込めないため出力結果がABCCCCC…となってしまう問題が発生する!//
        cout << ch << endl;
    }
    return 0;
}
//入力→ABC
//出力結果→ A
          B
           C

cinは改行('/n')と空白を削除する役割を持っている!
入力をEOFまで読み込む場合はwhile(cin >> ch)と書けばよい。
配列を作らないで、複数の文字を一文字ずつ読み込むためには(初めの1文字→次の2文字→…)while(1)でループさせるしかない!!
それが唯一の配列を使わない方法!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?