C++中输入一段字符,统计行数

2025-05-09 09:56:06
推荐回答(4个)
回答1:

C++实现如下:

#include"iostream"
using namespace std;
void main()
{
int line=0;
char c;
while((c=getchar())!=EOF)
if (c=='\n') line++;//判断是否换行。
cout<}

样例输入:

Hello world!

Hi.

Nice to meet you.

Goodbye.

See you.

^Z                                           (^Z是文件结束符,产生EOF。)

样例输出:

5

回答2:

#include
using namespace std;
int main()
{
char c;
int num=0;
while((c=getchar())!=EOF)
{
if(c=='\n') num++;
}
cout<return 0;
}
由于你是统计行数,所以只有以文件结束符结尾来跳出循环了,num即行数。

回答3:

#include "stdafx.h"
#include "iostream"
using namespace std;
#define OUT 0
#define IN 1
int main()
{
int c,nl,nw,nc,state;
state=OUT;
nl=nw=nc=0;
while((c=getchar())!=EOF)
{
++nc;
if(c=='\n')
++nl;
if(c==' '||c=='\n'||c=='\t')
state=OUT;
else if(state==OUT)
{
++nw;
state=IN;
}
}
cout<}

回答4:

この文言は、基言语仕様书に定义されていません。