繁体   English   中英

从函数中获取字符时,相当于cin.getline()。

[英]cin.getline() equivalent when getting a char from a function.

据我了解,cin.getLine获取第一个字符(我认为它是一个指针),然后获取该长度。 我在cin上烧焦时用过它。 我有一个函数,它返回一个指向数组中第一个字符的指针。 是否有将数组的其余部分转换为char的等效项,我可以使用整个数组。 我在下面解释了我要做什么。 该功能工作正常,但如果有帮助,我可以发布该功能。

cmd_str[0]=infile();// get the pointer from a function
cout<<"pp1>";
cout<< "test1"<<endl;
//  cin.getline(cmd_str,500);something like this with the array from the function                                                   
cout<<cmd_str<<endl; this would print out the entire array
cout<<"test2"<<endl;
length=0;
length= shell(cmd_str);// so I could pass it to this function   

您可以使用字符串流:

char const * p = get_data();  // assume null-terminated

std::istringstream iss(std::string(p));

for (std::string line; std::getline(iss, line); )
{
    // process "line"
}

如果字符数组不是以Null结尾的,而是具有给定的大小N ,则改为说std::string(p, N)

首先,如果cmd_strchar数组,并且infile返回指向字符串的指针,则第一个分配将给您一个错误。 它尝试将指针分配给单个字符。

您似乎想要的是strncpy

strncpy(cmd_str, infile() ARRAY_LENGTH - 1);
cmd_str[ARRAY_LENGTH - 1] = '\0';

我确保将字符串终止符添加到数组中,因为如果strncpy复制所有ARRAY_LENGTH - 1字符,它将不会附加终止符。

如果cmd_str是一个适当的数组(即像char cmd_str[ARRAY_LENGTH];那样声明),则可以在我的示例中使用sizeof(cmd_str) - 1而不是ARRAY_LENGTH - 1 但是,如果将cmd_str作为函数的指针传递,则将不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM