2013-10-20 291 views
0

我想从用户请求单词,然后使用'strcpy'将单词从字符串转换为字符。然后我想确定单词中所有字母的ASCII码的总和。将字符串转换为字符ascii

但是,我有困难。我不明白我该怎么做。这是我迄今为止能够做到的。

#include <iostream> 
#include <time.h> 
#include <stdlib.h> 
#include <string.h> 

using namespace std; 

int main() 
{ 
    string word; 
    cout << "Enter word: "; 
    getline(cin, word); 
    /* 
     char w[word]; 
     strcpy(w,word.c_str()); 
     int ('A'); 
     cout<<char(65); 
    */ 
    return 0; 
} 

评论部分是我一直在尝试转换的地方。我从工作表中复制了代码。即使它确实有效,我也不知道如何以及它的意义。

感谢您的帮助。

+6

你为什么要这么做这个? – 0x499602D2

+0

您无法制作具有运行时间确定大小的内置阵列。 – chris

+0

这是我的问题提示: 询问用户单词(使用文本框)。然后确定单词中所有字母的ASCII码的总和,并在某个标签中声明它。你将需要一个string.h包括,你需要使用'strcpy'函数将字(从用户获得的)从字符串转换为字符。 – user2877477

回答

3
char w[word]; 
strcpy(w, word.c_str()); 

char w[word]不正确。方括号表示大小,它必须是一个常量积分表达式。 wordstd::string类型,所以这不合逻辑也不实际。也许你是想:

char w = word; 

但仍然不会起作用,因为word是一个字符串,而不是一个字符。在这种情况下正确的代码是:

char* w = new char[word.size() + 1]; 

也就是说,您使用char*分配的内存w。然后,您使用word.size() + 1初始化堆分配的内存总计这些字节。当你使用完w不要为强制性delete[]忘记:

delete[] w; 

但是请注意,使用原始指针,在这种情况下,不需要明确new。你的代码可以很容易被清理成以下:

#include <numeric> 

int main() 
{ 
    std::string word; 

    std::getline(std::cin, word); 

    int sum = std::accumulate(word.begin(), word.end(), 0);     /* 
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^     */ 

    std::cout << "The sum is: " << sum << std::endl; 
} 
+0

+ std :: accumulate()'! –

+0

固定标题(不在'') – MSalters

+0

@ MSalters哇,这很奇怪。从未见过''之前...... – 0x499602D2

0

你并不需要使用strcpy()(或使用char *可言,对于这个问题),但是这会使用char指针做你的计数:

#include <iostream> 
#include <string> 

int main() { 
    std::string word; 

    std::cout << "Enter word: "; 
    std::cin >> word; 

    const char * cword = word.c_str(); 
    int ascii_total = 0; 

    while (*cword) { 
     ascii_total += *cword++; 
    } 

    std::cout << "Sum of ASCII values of characters is: "; 
    std::cout << ascii_total << std::endl; 

    return 0; 
} 

输出:

[email protected]:~/src/cpp/scratch$ ./asccount 
Enter word: ABC 
Sum of ASCII values of characters is: 198 
[email protected]:~/src/cpp/scratch$ 

如果你真的想使用strcpy(),我会离开它作为一个练习你MODIF y上面的代码。

这里有一个更好的方式来做到这一点,只是用std::string(和C++ 11,显然意味着你的系统使用ASCII字符放在第一位置):

#include <iostream> 
#include <string> 

int main() { 
    std::string word; 

    std::cout << "Enter word: "; 
    std::cin >> word; 

    int ascii_total = 0; 
    for (auto s : word) { 
     ascii_total += s; 
    } 

    std::cout << "Sum of ASCII values of characters is: "; 
    std::cout << ascii_total << std::endl; 

    return 0; 
} 
+0

感谢您的帮助。 如果你可以修改代码到strcpy(),那将是非常有用的。我真的不知道该怎么做。 反正非常感谢。 – user2877477

+0

这个问题的其他答案已经告诉你如何。 –