c++中如何将输入的字符串(不知长度)存入数组中?最好用代码回答.

如题所述

#include<iostream>
#include<string>
#include<windows.h>
using namespace std;
int main()
{
string str;
char temp;
cout<<"输入字符串,按回车键结束输入"<<endl;
while((temp=cin.get())!='\n')
{
str +=temp;
}
const int LEN =str.length();
char* dest = new char[LEN];//根据输入字符串的长度,创建字符数组
for(int i = 0;i<LEN;i++) //将字符串保存到字符数组中
{
dest[i]=str[i];
cout<<dest[i];
}
delete dest;
system("pause");
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-05
如果可以使用String类的话那很方便了
先用String类接受输入
再转换为char*

对于“不知长度”的输入,如果我的输入超出了内存的限制,不也是会Fail的么,所以一定有某种“限制”输入的长度。追问

有长度限制,不过在长度限制之内不知长度,能用代码演示一下吗?谢谢.

第2个回答  2013-05-05
char s[255];
cin.getline(s,255)

后边可以用 strlen(s) 获取到实际长度追问

能用代码演示一下吗?谢谢.

追答#include <iostream>
#include <string>
using namespace std;
int main()
{
    char s[255];
    cout<<"请输入不超过 255 个字符的字符串";
    cin.getline(s,255);
    cout<<"你输入的字符串为:"<<s<<endl;
    cout<<"该字符串长度为:"<<strlen(s)<<endl;
    return 0;
}

第3个回答  2013-05-05
#包括
#包括中

无效的主要()

{

INT I,J;

个char [4] [ 20],[20];

(I = 0; <4; + +)

得到([]);

(I = 0 <4; + +)

(J = 0; J <3-I,J + +)

(STRCMP([J],[J +1)] > 0)

{

STRCPY(T,S [J]);

STRCPY([J],[J +1]);,

STRCPY([ +1],T);

}

的printf(“排序后:\ N”);

(i = 0; <4 + +)

看跌期权([]);
}
第4个回答  2013-05-05
#include<stdio.h> void main() {char ch[100]; scanf("%s",ch); printf("%s",ch);}追问

那个我是学c++的,看不懂c,能用c++编一段吗?谢谢.

追答

会动态定义长度了么(new)

追问

动态定义长度?不大清楚.

追答

我用手机不太好打代码,明天再把代码给你把,实现方法其实挺多的……
方案1:
#include
#include
using namespace std;
int main()
{
string str;
cin>>str;
cout
#include
using namespace std;
int main()
{
char s[255];
cout
using namespace std;
int main()
{
char s[255];
cout>s;//注意!!
cout<<"你输入的字符串为:"<<s<<endl;
return 0;
}