读取字符串的长度,然后反转该字符串
Reading a length of a string, then inverse/reverse the string
基本上,我已经成功地写下了这篇文章,并且我成功地反转了一个单词!但是,当我试图反转包含2个或更多单词的字符串时,我无法获得输出。有人知道如何解决这个问题,或者知道一些技巧吗?
#include <iostream>
using namespace std;
int main()
{
char words[100];
int x, i;
cout<<"Enter message : ";
cin>>words;
x = strlen(words);
//This two line is used to reverse the string
for(i=x;i>0;i--)
cout<<words[i-1]<<endl;
system("pause");
return 0;
}
问题不在于char array与std::string,而在于输入法。
将cin>>words
更改为cin.getline(words, sizeof(words), 'n');
我猜这个任务是一个习惯数组的任务,所以坚持使用char数组——否则,是的,std::string是易于使用的方法。
您可以使用std::string
代替C字符数组,也可以使用string::reverse_iterator以相反的顺序读取单词。要读取用空格分隔的多个单词,需要使用std::getline。
std::string words;
std::getline(std::cin, words, 'n'); //if you read multiple words separated by space
for (string::reverse_iterator iter = str.rbegin() ; iter != str.rend(); ++iter)
{
std::cout << *iter;
}
或使用std::reverse
std::reverse(words.begin(), words.end());
使用cin.getline(words,99)
而不是cin>>words
,因为cin>>字将只获得第一个空白处的char数组。
相关文章:
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 字符串变成链表,然后检查括号余额
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何根据长度然后字母顺序对数组字符串进行排序?
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 将无符号字符转换为字符串,然后再次转换为无符号字符
- 在构造函数中创建一个字符串数组,然后在主函数中使用它
- C 从文件中读取文本,然后将字符串解析为int数组
- JNI将字符串从Java传递到C ,然后将C 字符串传递给字符串数组
- C :在字符串中找到一个char,然后在先前的char之后找到另一个字符
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 文字符号和字符串变量之间的串联然后返回常量字符*