我有代码,但它以大写字母打印字母,但之后也会打印一些奇怪的字符。我只是想知道如何获得这些信件。
使用namespace std;
int main()
{
const int SIZE = 81; // Constant for size of an array
const int MIN_LOWERCASE = 97; // Start of lowercase letters in ASCII
const int MAX_LOWERCASE = 122; // End of lowercase letters in ASCII
char line[SIZE]; // Initializing character line for input
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
for (int count = 0; count < SIZE; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
cout << endl;
system("pause");
return 0;
}
答案 0 :(得分:1)
您需要使用您阅读的文本的实际大小。否则,您将打印额外的字符。
for (int count = 0; count < strlen(line); count++)
您可能需要#include <cstring>
才能使用strlen()
。
答案 1 :(得分:1)
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
int strLen=strlen(line)
for (int count = 0; count < strLen; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
无论字符串大小是多少,Ypur循环都会运行80次。
答案 2 :(得分:1)
在C ++中这样做的惯用方法是
#include <string>
#include <locale>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::locale loc(""); //< the current system locale
std::string line; //< will contain the input line
std::cout << "Enter a string of 80 or fewer characters:\n";
std::getline(std::cin,line);
std::string lower; //< will contain the output
// This is the "key" of everything
std::transform(line.begin(),line.end(), // transform the entire input...
std::back_inserter(lower), // by writing into the back of the output string ...
[&loc](auto c){ return std::tolower(c,loc); }); // the result of std::tolower applied to all character, using the system locale
std::cout << "The transformed string is:\n" << lower << std::endl;
return 0;
}
// look ma! No pointers, array sizes, overflows and explicit memory management.
// And works consistently with the language your computer is set up.
答案 3 :(得分:1)
实际上,char []的getline / cin / scanf等函数解释如下:
char c[10];
初始化字符串。输入是&#34; abcd&#34;。0<=i<=4
处改变,因为输入的长度为4。c = { 'a', 'b', 'c', 'd', '\0', ?, ?, ?, ?, ?}
。 (?表示未知值)因此,如果您只在c[i] != '\0'
进行循环,则可以修复该错误。