注册 登录
编程论坛 C++教室

C++ 输入多行字符串以ctrl+z结束问题

UJN923600725 发布于 2018-06-20 02:02, 2749 次点击
题目描述
编写函数完成字符串反转。要求必须使用C++字符串,必须使用函数
输入

输入有多行,每一行代表一个字符串。 输入行数不确定,以ctrl+z结束。
输出
输出翻转后的字符串。每个字符串占一行。
样例输入
who's your daddy
my daddy is Li Gang
样例输出
yddad ruoy s'ohw
gnaG iL si yddad ym
提示

对于多行判断,可采用while(getline(cin, str))来实现,如果getline获取到ctrl+z,则退出while循环。





于是我写了这样一个代码

程序代码:
#include <iostream>
#include <string>
using namespace std;

string invert(string str,int n)
{
    char temp;
    for(int i=0;i<n/2;i++)
      {
        temp=str[i];
        str[i]=str[n-1-i];
        str[n-1-i]=temp;
      }
    for(int j=0;j<n;j++)
    cout<<str[j];
    cout<<endl;
}

int main()
{
    string str;
    int n;
    while(getline(cin,str))
    {   
        n=str.size();
        invert(str,n);
    }
}



问题1 : 输入样例who's my daddy ,下一行确实出现了yddad ruoy s'ohw ,而当我准备输入第二行样例的时候他顿了一下结束了(输入任意键继续那个)

问题2 ; 这个以ctrl+z结束要怎么操作啊

求大佬讲解一下~!蟹蟹~!
2 回复
#2
rjsp2018-06-20 08:32
我编译报错,error C4716: 'invert' : must return a value
你用的是什么编译器?

BTW:windows的控制台才是以ctrl+z结束,unix/linux是ctrl+d,这不是C/C++相关的问题,这是别人系统软件的设定。

程序代码:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

int main( void )
{
    for( string str; getline(cin,str); )
        copy( str.rbegin(), str.rend(), std::ostream_iterator<char>(cout,"") ) = '\n';
}

#3
UJN9236007252018-06-20 09:12
回复 2楼 rjsp
用的dev c++呀
1