C++ 无法使用getline()输入字符串。它只读取一个字符串 char*name[4]; int j=0; while(cin.getline(name[j],80))//输入给定:you(ent)me(ent)he(ent)she 我做了一点更正。它在我的电脑上工作 char* name[4]; int j=0; while(cin.getline(name[j],80))//input given:you(ent)me(ent)he(ent)she cout<<name[j++]; char*name[4]; 对于(int i=0;i

C++ 无法使用getline()输入字符串。它只读取一个字符串 char*name[4]; int j=0; while(cin.getline(name[j],80))//输入给定:you(ent)me(ent)he(ent)she 我做了一点更正。它在我的电脑上工作 char* name[4]; int j=0; while(cin.getline(name[j],80))//input given:you(ent)me(ent)he(ent)she cout<<name[j++]; char*name[4]; 对于(int i=0;i,c++,string,getline,C++,String,Getline,另一个问题是,当输入结束时,当j=4时,您仍将尝试执行cin(getline(name[j],80),但您将名称[4]作为参数传递,这可能是另一个UB的原因,即使您事先正确分配了内存 其他,然后用C++编写,所以使用C++字符串和向量代替C数组。 这可以通过字符串和std::getline轻松完成: char* name[4]; for (int i = 0; i < 4; i++) name[i] = new char[80]; int j = 0; while (j <

另一个问题是,当输入结束时,当j=4时,您仍将尝试执行
cin(getline(name[j],80)
,但您将名称[4]作为参数传递,这可能是另一个UB的原因,即使您事先正确分配了内存

其他,然后用C++编写,所以使用C++字符串和向量代替C数组。 这可以通过字符串和std::getline轻松完成:

char* name[4];
for (int i = 0; i < 4; i++)
    name[i] = new char[80];
int j = 0;
while (j < 4)
{
    cin.getline(name[j], 80); //input given:you(ent)me(ent)he(ent)she
    cout << name[j++] << endl;
}
#包括
#包括
使用名称空间std;
int main(){
载体名称;
字符串名;
while(getline(cin,name)){
名称。推回(名称);

cout问题:您没有正确分配内存。您正在声明指针数组,而不是c样式字符串数组

可能的解决方案:您需要首先阅读指针和内存分配。您可以使用以下代码,将内存首先分配给您声明的四个指针
名称[0]
名称[1]
名称[2]
名称[3]

#include <iostream>
#include <vector>
using namespace std;

int main(){
    vector<string> names;
    string name;
    while(getline(cin, name)){
        names.push_back(name);
        cout<<name<<endl;
    }
    return 0;
}
char*name[4];
对于(int i=0;i<4;i++)
{
名称[i]=新字符[80];
}
或者,您可以使用二维数组,其代码如下所示:

char* name[4];
for (int i = 0; i < 4; i++)
{
    name[i] = new char[80];
}
字符名[4][80];
int j=0;

虽然(Ju有指针数组,但指针指向何处?使用STD::vector和STD::string。没有人有时间来处理PoTest.Unice),可以建议使用一些源来加强C++ + KrsZIT这一区域,将单数和复数作为变量的名称不是一个好主意。很容易出错。>?另外,请阅读
for
循环是否比
while
循环好?@Ed Heal,感谢您指出我的粗略编码。我会做得更好。
char name[4][80];
int j=0; 
while(j<4 && cin.getline(name[j],80))
{
    cout<<name[j++];
}