C和c++中的字符串输入

String input in C and C++

本文关键字:字符串 输入 c++      更新时间:2023-10-16

我想用C或c++写一个程序,要求用户在运行时输入用户在不同时间给定的不同长度的字符串(空格分隔或非空格分隔),并将其存储到数组中。请给我C和c++的样例代码

1st run:
Enter string
Input: Foo 

现在是char array[]="foo";

2nd run:
Enter string
Input:
Pool Of

现在char array[]="Pool Of";

I have try:

#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。

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

您需要从stdin中读取字符,直到遇到某个结束符(例如换行符),并将该字符附加到临时字符数组(char*)的末尾。对于所有这些,您应该手动控制溢出并根据需要扩展(重新分配+复制)数组。

当您按下enter键时,您必须照顾额外的字符,该字符也馈送给cin.getline(),如果照顾到这一点,它将正常工作。这是cin在Windows中的行为。在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 !