C++字符数组,将字符向后放置作为输出
C++ Character Array, Placing Characters Backwards as an Ouput
我需要这个作业的帮助,它来自新学习者的计算机编程课程。这是一个字符数组C++代码被破坏了,我必须修复它。除了,我已经坚持了很长时间了,我需要一些帮助。如果有人能帮我解决这个问题,那就太好了!谢谢!
#include"stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main()
{
string word[20];
char inputword;
int x;
cout<<"Enter a word ";
cin>>inputword;
if(word[0] = 'a' || word[0] = 'e' || word[0] = 'i' ||
word[0] = 'o' || word[0] = 'u')
cout<<"Words that start with vowels are not easily translated to Pig Latin"<<endl;
else
{
cout<<"In Pig Latin: ";
while(word[x] != NULL)
{
cout<<word[x];
++x++;
}
cout<<word[0]<<"ay"<<endl;
}
}
只是为了咧嘴笑,我修改了你的代码才能工作。 希望这有帮助。
#include"stdafx.h"
#include<iostream>
// #include<string> // working w/char arrays, don't need std strings
#include <cstring> // include this file so we can use strlen (c-style strings)
using namespace std;
int main()
{
char word[20]; // you're working with a char array (not string array)
// char inputword; // you don't need a separate input data structure
int x;
cout<<"Enter a word ";
cin>>word; // input directly into the word array
// use == to compare for equality, using = is assigning to word[0]
if(word[0] == 'a' || word[0] == 'e' || word[0] == 'i' ||
word[0] == 'o' || word[0] == 'u')
cout<<"Words that start with vowels are not easily translated to Pig Latin"<<endl;
else
{
cout<<"In Pig Latin: ";
// get the size of the word:
// x = strlen(word);
// work backwards through the array and print each char:
for(int i=strlen(word); i>=0; --i)
{
cout << word[i];
}
cout << "ay" << endl;
// use the for loop shown above instead of this
// while(word[x] != NULL)
// {
// cout<<word[x];
// ++x++;
// }
// cout<<word[0]<<"ay"<<endl;
}
}
所以首先要确定给定程序中的错误:
-
你需要一个 char 类型的数组,在给定的程序中,数组被声明为字符串类型,另一个不是数组的变量被声明为字符。所以你需要的是:
char word[20];
-
接受输入时,需要使用声明的字符数组:
cin>>word;
-
=
和==
是有区别的,后者用于比较,前者用于赋值。因此,如果您想比较a
是否与b
相同,那么您会做if(a==b)
但如果您想将b
的值放入a
中,您将a = b
。请务必注意if(a = b)
如果a
和b
都是有效变量,则始终为真。因此,您需要将 if 语句更改为:if(word[0] == 'a' || word[0] == 'e' || word[0] == 'i' || word[0] == 'o' || word[0] == 'u')
-
最后,要向后输出字符串,您只需从数组中的最后一个字符开始打印到第一个字符。要获取数组的最后一个索引,请使用 strlen 函数获取字符数组的长度,该长度将与最后一个索引相同:
n = strlen(word);
然后从那里倒退:
while(n>=0) { cout<<word[n]; n--; }
这将以相反的顺序为您提供字符数组。
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 字符的输入/输出操作
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- C++输出奇怪的字符而不是数字 (Windows)
- 如何存储 unicode 字符并将其输出到文件?
- C++中附加的字符*的奇怪输出
- 来自无符号字符缓冲区的虚拟输出
- 将未签名的字符写入输出文件
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 如何在C++中正确地将我的语言字符输出到HTML文件中
- x86 上的指针大小和奇怪的字符输出
- 如何修复C++中的随机字符输出?
- Visual Studio-怪异的字符输出
- 需要我当前的字符输出,这是它在C++中的整数值
- 宽字符输出结果
- 将字符输出随机化为文本文件
- C++和printf-奇怪的字符输出
- 显示无符号字符*和有符号字符*输出的结果是否完全相同
- 下一个回文 .奇怪的字符输出
- 不要将宽字符输出到命令提示符