2 qq 39637196 qq_39637196 于 2017.08.28 10:59 提问

c++不确定个数的字符串输入
c++

如何设置输入不确定个数的字符串?中间会用空格分开,输入结束按回车键

5个回答

SeaTalks
SeaTalks   2017.08.28 13:38
已采纳

那给你个例子吧:

 #include <stdio.h>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;

vector<string> split(char* str,const char* c)
{
    char *p;
    vector<string> res;
    p = strtok(str,c);
    while(p!=NULL)
    {
        res.push_back(p);
        p = strtok(NULL,c);
    }
    return res;
}

int main() {
    char c;
    vector<char> chars;
    while((c=getchar()) != '\n'){
        chars.push_back(c); 
    }
    chars.push_back('\0');
    char *str = new char[chars.size()+1];
    strcpy(str, &(*chars.begin()));
    c=' ';
    vector<string> strs = split(str, &c);
    for (int i=0;i<strs.size();++i){
        cout << strs[i]<<endl;
    }
    delete str;
    return 0;
}

输入为:

a b asdf lkasj ;aslkdf asdf k

输出为:

a
b
asdf
lkasj
;aslkdf
asdf
k

RAM_MAM
RAM_MAM   2017.08.28 13:14

gets + strtok

SeaTalks
SeaTalks   2017.08.28 11:04

 vector<string> strs;

 strs.push_back(你的字符串);
qq_39637196
qq_39637196 回复SeaTalks: 请问如何退出字符串的输入啊?好像程序会一直等我输入
3 个月之前 回复
wood_179811
wood_179811   2017.09.03 11:42

楼上竟然使用了 vector 真是 小试牛刀啊 哈

zhang_guyuan
zhang_guyuan   2017.09.04 16:09

getchar()就行哈

Csdn user default icon
上传中...
上传图片
插入图片