我想用C或C++编写一个程序,要求用户在运行时以不同的时间输入字符串,这些时间由用户给出的不同时间(空格分隔或非空格分隔)和将它存储到一个数组中。请为我提供C和C++的示例代码。C和C++中的字符串输入
例如
1st run:
Enter string
Input: Foo
现在char array[]="foo";
2nd run:
Enter string
Input:
Pool Of
现在char array[]="Pool Of";
我曾尝试:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin>>p;
cout<<p<<endl;
cout<<p;
return 0;
}
但是当字符串是空格分隔它不工作。
我也试过这个,但它也没有工作。
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin.getline(p,n);
cout<<p<<endl;
cout<<p;
return 0;
}
我试过用getline –
发布代码并解释你有什么困难。也是这应该是C或C++? –
它可能是C或C++的任何东西。 –