c++ - 为什么 c++ 不包括\n 而 python 不是

标签 c++ python

<分区>

我写了一段简单的代码来输出 ascii 值的总和,在 c++ 和 python 中,给定一个输入文件。

对于相同的输入文本文件,c++ 部分似乎已经排除了 '\n' 而 python 部分确实包含了 '\n' 作为其计算的一部分。

我想知道我的代码中是否有任何我忽略的步骤。

代码片段:

    import sys

    try:
         f=open(sys.argv[1]).read()
    except:
        print " file not found \n"  
        sys.exit()
    sum=0
    for line in f:
       for character in line:
          try:
        if character=='\n':
            pass
        else:
            print character
            sum+=ord(character)

    except:
        print "failed \n"
        pass


     print "The sum is %d \n" %sum

C++ 部分是:

    #include "iostream"
    #include "fstream"
    #include "string"
    int k;
    int main(int argc, char *argv[])
    {
    int sum=0;
    std::string line;
    std::ifstream myfile (argv[1]);
    if (myfile.is_open())
      {while (myfile.good())
        {
        getline (myfile,line);
        for (k=0;k<(line.length());k++)
            {
                sum=sum+int(line[k]);
            }
    }
std::cout<<" The total sum is : " <<sum<<std::endl;
}
  else std::cout<< "Unable to open file ";
  return 0;
  }

最佳答案

根据 std::getline() [string.io]§7 的规范:

extracts characters from is and appends them to str ... until any of the following occurs:

  • ...
  • traits::eq(c, delim) for the next available input character c (in which case, c is extracted but not appended)

(强调我的)。

这意味着当 getline 遇到分隔符(默认为 \n)时,它会将其从流中移除,但不会将其存储在字符串中。

至于直接回答您的“为什么”问题:因为它就是这样设计的。

关于c++ - 为什么 c++ 不包括\n 而 python 不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067127/

相关文章:

java - 最佳实践 : network communication

python - Buildbot:动态创建新的 Builder 或 BuilderConfig 或项目

python - Matplotlib 子进程/后端问题

c++ - 在头文件中设置的所有文件中全局使用变量

c++ - 在cplusplus中使用fstream时,这个程序有什么问题

python - Komodo IDE 7 在 Ubuntu 11.10 上崩溃

python - 当使用 ChromeDriver 和 Selenium 设置最大属性时,无法使用 send_keys 将日期作为文本发送到日期选择器字段

c++ - 带有 getline 的慢 istringstream

c++ - fstream 代码没有在我的桌面上创建文件

c++ - 容器末尾和指向内部项目的迭代器之间的区别。 C++