C++ Primer(第5版) 练习 12.24
练习 12.24 编写一个程序,从标准输入读取一个字符串,存入一个动态分配的字符数组中。描述你的程序如何处理变长输入。测试你的程序,输入一个超出你分配的数组长度的字符串。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************
> File Name: ex12.24.cpp
> Author:
> Mail:
> Created Time: Fri 19 Apr 2024 10:45:08 AM CST
************************************************************************/
#include<iostream>
#include<string>
#include<memory>
using namespace std;
int main(){
unique_ptr<char[]> strArr(new char[5]);
string str;
cout<<"Enter string: ";
getline(cin, str);
size_t len = str.length();
unique_ptr<char[]> newStr(new char[len+1]);
newStr = move(strArr);
strArr.release();
size_t j = 0;
for(size_t i = 0; i < len; ++i){
newStr[j++] = str[i];
}
newStr[j] = '\0';
cout<<"String: ";
for(size_t i = 0; i < len; ++i){
cout<<newStr[i];
}
cout<<endl;
newStr.release();
return 0;
}