[英]Formatting C-strings
The program is supposed to use a function that accepts a pointer to a C-string as an argument and capitalizes the first character of each sentence in the string. 程序应该使用一个函数来接受一个指向C字符串的指针作为参数,并将字符串中每个句子的第一个字符大写。 I'm having trouble with the output. 我输出有问题。 This is my code: 这是我的代码:
#include "stdafx.h"
#include <cstring>
#include <iostream>
using namespace std;
void Capitalize(char *);
int _tmain(int argc, _TCHAR* argv[])
{
char sentence[1000];
cout << "Please enter a sentence: " << endl;
cin.getline(sentence, 1000);
char *sentencePtr = sentence;
Capitalize(sentencePtr);
cout << sentencePtr;
cin.get();
return 0;
}
void Capitalize(char *str){
int count;
for(count = 0; count < strlen(str); count++){
if(str[count] = '.'){
count += 2;
toupper(str[count]);
}
}
}
toupper(str[count]);
This converts the character to upper case and then throws the result away. 这会将字符转换为大写,然后将结果抛出。 You want: 你要:
str[count]=toupper(str[count]);
Also, this is an assignment: 此外,这是一项任务:
if(str[count] = '.'){
You want a comparison: 你想要一个比较:
if(str[count] == '.'){
That's a good go, but toupper
returns the uppercase version of a character, it does not modify the argument that is provided. 这是一个很好的去,但toupper
返回一个字符的大写版本,它不会修改提供的参数。 Try this: 尝试这个:
// note, you must use '==', not '='
if(str[count] == '.')
{
count += 2;
str[count] = toupper(str[count]);
}
As an exercise, try and avoid using C-strings altogether, and see if you can do it using only the std::string
class. 作为练习,尝试避免完全使用C字符串,并查看是否可以仅使用std::string
类来完成。 Ultimately, you will realise that using std::string
is much easier than using plain old C-strings. 最终,您将意识到使用std::string
比使用普通的旧C字符串容易得多。
You're using an assignment operator (=) not a comparison (==), you need to change: 您使用的是赋值运算符(=)而不是比较(==),您需要更改:
if(str[count] = '.'){
To: 至:
if(str[count] == '.'){
As others have indicated, your use of toupper isn't quite right either, as it returns the new value, it doesn't modify the orignal as it doesn't take a reference. 正如其他人所指出的那样,你对toupper的使用也不是很正确,因为它返回新值,它不会修改orignal,因为它没有参考。
str[count] = toupper(str[count]);
You have a typo here: 你有一个拼写错误:
if(str[count] = '.')
should be: 应该:
if(str[count] == '.')
Also, str[count] = toupper(str[count]);
另外, str[count] = toupper(str[count]);
Looks like your comparison is wrong. 看起来你的比较是错误的。 Try changing 尝试改变
if(str[count] = '.')
to 至
if(str[count] == '.'){
remember -> = is a assignment operator == is a comparison operator 记住 - > =是赋值运算符==是比较运算符
(I think your Capitalize func is wrong, but i dont know if its how you want it to be) (我认为你的资本化功能是错误的,但我不知道你的想法是否如此)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.