试图将未知数量的字符串推入向量,但我的cin循环不会终止

问题描述 投票:10回答:3

我试图从cin获取字符串作为输入,然后每次将字符串推入向量。但是,即使我在所有输入的末尾加上'\',我的循环也不会终止。

int main(void) {
    string row;
    vector<string> log;
    while (cin >> row) {
        if (row == "\n") {
            break;
        }
        log.push_back(row);
    }
    return 0;
}

我试过用(cin >> row)替换(getline(cin,row)),但它没有任何区别。我尝试过使用stringstream,但我真的不知道它是如何工作的。我该如何解决这个问题?

c++ cin
3个回答
10
投票

正如@SidS评论的那样,空格被丢弃了。所以你必须考虑另一种策略。你可以改为检查row是否为空。但这只适用于std::getline

#include <vector>
#include <string>
#include <iostream>

int main() {
    std::string row;
    std::vector<std::string> log;
    while (std::getline(std::cin, row)) {
        if (row.empty()) {
            break;
        }
        log.push_back(row);
    }
    std::cout << "done\n";
}

OP,如果你想保存单个单词(而不是整行),你可以使用regex在输入后单手将每个单词推入log

#include <vector>
#include <string>
#include <iostream>
#include <regex>

int main() {
    const std::regex words_reg{ "[^\\s]+" };

    std::string row;
    std::vector<std::string> log;
    while (std::getline(std::cin, row)) {
        if (row.empty()) {
            break;
        }
        for (auto it = std::sregex_iterator(row.begin(), row.end(), words_reg); it != std::sregex_iterator(); ++it){
            log.push_back((*it)[0]);
        }
    }
    for (unsigned i = 0u; i < log.size(); ++i) {
        std::cout << "log[" << i << "] = " << log[i] << '\n';
    }
}

示例运行:

hello you
a b c d e f g
18939823
@_@_@ /////

log[0] = hello
log[1] = you
log[2] = a
log[3] = b
log[4] = c
log[5] = d
log[6] = e
log[7] = f
log[8] = g
log[9] = 18939823
log[10] = @_@_@
log[11] = /////

2
投票

如果你想存储来自std::cin的一行代码,用operator>><iostream>重载标准机制分隔(即用空格/换行符拆分),你可以这样做:

std::string line;
std::getline(std::cin, line);
std::stringstream ss{line};

const std::vector<std::string> tokens{std::istream_iterator<std::string>{ss},
    std::istream_iterator<std::string>{}};

请注意,这不是最有效的解决方案,但它应该按预期工作:只处理一行并使用现有机制将此行拆分为单独的std::string对象。


1
投票

您无法使用字符串的istream& operator >>读取换行符。此运算符忽略空格,永远不会返回字符串"\n"。考虑使用getline代替。

© www.soinside.com 2019 - 2024. All rights reserved.