2011-07-10 50 views
0

我想用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; 
} 
+0

我试过用getline –

+2

发布代码并解释你有什么困难。也是这应该是C或C++? –

+0

它可能是C或C++的任何东西。 –

回答

2

使用getline。

看看一个这个例子:
http://www.cplusplus.com/reference/iostream/istream/getline/

+0

但是它并没有要求用户给出字符串的长度,而是在编译时静态声明了一个char数组。我想在运行时初始化这个arrray。 –

+1

@ gautam-kumar我很确定你可以做到这一点,而无需我为你写程序。像您在发布的代码中一样分配缓冲区。然后使用getline,如本例所示。 – log0

+0

:我已经尝试过了,但没有工作。请查看它我也在问题中给出了它 –

0

需要,直到你遇到一些终止(换行符为例)从stdin读取字符和字符添加到您的临时字符数组的结尾(字符* )。对于所有这些,您应该手动控制溢出并根据需要扩展(重新分配+复制)数组。

+0

欢迎来到堆栈溢出 – Tom

0

当你按下输入时,你必须照顾额外的字符,也是喂给cin.getline()如果这是照顾它将工作正常。这是Windows中cin的行为。可能在Linux中发生。如果你在Windows中运行这个代码,它会给你你想要的。

#include <iostream> 
using namespace std; 

int main() { 
    int n; 

    // Take number of chars 
    cout<<"Number of chars in string: "; 
    cin>>n; 

    // Take the string in dynamic char array 
    char *pStr = new char[n+1]; 
    cout<<"Enter your string: "<<endl; 

    // Feed extra char 
    char tCh; 
    cin.get(tCh); 

    // Store until newline 
    cin.getline(pStr, n+1); 
    cout<<"You entered: "<<pStr<<endl; 

    // Free memory like gentle-man 
    delete []pStr; 

    // Bye bye 
    return 0; 
} 

HTH!

+0

不是那么绅士 - 应该用'delete [] pStr' ;-) – Tim

+0

我编辑它。 :) –