![](/img/trans.png)
[英]How to insert white spaces as input into char array with std::cin
[英]std::cin input with spaces?
#include <string>
std::string input;
std::cin >> input;
用户想要输入“Hello World”。 但是cin
在两个词之间的空格处失败了。 我怎样才能让cin
占据整个Hello World
?
我实际上是在用结构做这个,而cin.getline
似乎不起作用。 这是我的代码:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
这会产生错误。 有任何想法吗?
它不会“失败”; 它只是停止阅读。 它将词汇标记视为“字符串”。
使用std::getline
:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
请注意,这与std::istream::getline
不同,后者适用于 C 风格的char
缓冲区而不是std::string
。
更新
您编辑的问题与原始问题几乎没有相似之处。
您试图getline
进入int
,而不是字符串或字符缓冲区。 流的格式化操作仅适用于operator<<
和operator>>
。 要么使用其中一个(并针对多字输入进行相应调整),要么使用getline
并事后词法转换为int
。
你必须使用cin.getline()
:
char input[100];
cin.getline(input,sizeof(input));
标准库提供了一个名为ws
的输入 function ,它使用来自输入 stream 的空格。 你可以像这样使用它:
std::string s;
std::getline(std::cin >> std::ws, s);
利用:
getline(cin, input);
function 可以在
#include <string>
您想在 cin 中使用 .getline function。
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
以here为例。 查看它以获取更多信息和示例。
C 方式
您可以使用在 cstdio(stdio.h in c) 中找到的gets
function:
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
C++ 方式
get 在gets
中被删除。
[推荐]:您可以使用string.h
中的getline(cin,name)或iostream
本身中的cin.getline(name,256) 。
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
如何从输入中读取字符串?
您可以使用std::cin
读取单个以空格结尾的单词,如下所示:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
请注意,没有明确的 memory 管理,也没有可能溢出的固定大小的缓冲区。 如果你真的需要一整行(而不仅仅是一个单词),你可以这样做:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
我宁愿使用以下方法来获取输入:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
它实际上超级容易使用,而不是为包含空格字符的字符串定义数组的总长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.