簡體   English   中英

C 和 C++ 中的字符串輸入

[英]String input in C and 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。

看看這個例子:
http://www.cplusplus.com/reference/iostream/istream/getline/

您需要從標准輸入讀取字符,直到遇到一些終止符(例如換行符)和 append 字符到臨時字符數組(char *)的末尾。 對於所有這些,您應該手動控制溢出並根據需要擴展(重新分配+復制)數組。

當您按下回車鍵時,您必須處理也提供給 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM