gpt4 book ai didi

c++ - std::getline在函数内部不起作用

转载 作者:行者123 更新时间:2023-12-02 10:13:16 25 4
gpt4 key购买 nike

我具有以下功能:

void my_func(std::string b){
std::string name;
std::cout << "Please enter the name\n";
std::getline(std::cin, name, ',')
b = name;
std::cout << "b = " << b << "\n";
}
此函数的问题是,当我将其放在头文件中时,该代码的 std::getline(std::cin, name, ',')行未运行,即,它不要求用户输入,但继续打印b。我不明白为什么会这样。
如果我在main中编写上述代码的第2至6行,则可以正常工作。但是,如果我将这些行放在函数中,它将无法正常工作。
#include <iostream>
#include <string>
int main(){
std::string name, b;
std::cout << "Please enter the name\n";
std::getline(std::cin, name, ',')
b = name;
std::cout << "b = " << b << "\n";
return 0;
}

最佳答案

您正在修改参数的副本:
代替:

void my_func(std::string b){ //<--semantic meaning "take a copy of b"
改成:
std::string my_func() // <-- returning a std::string by value
{
std::string b;
//...
return b;
}

请注意,“按引用返回”也是一个选项,但是它在语义上更加复杂(有些人可能会说更多),因此不应成为解决方案的首选。但是,我在这里显示它是因为您仍然需要了解这个概念并全面引用:
void my_func(std::string& b){ //<-a reference to a string
另外,当对象的副本可能很昂贵时,const引用(例如 const std::string& b)是传递参数的常用方法。

关于c++ - std::getline在函数内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com