简体   繁体   English

字符串不会打印

[英]String won't print

I've been doing programming challenges on coderbyte and while doing one, ran into an issue. 我一直在对coderbyte进行编程挑战,而在进行挑战时遇到了一个问题。 I want to isolate a word from a string, do some checks on it and then move to another word. 我想从字符串中分离出一个单词,对其进行一些检查,然后再移动到另一个单词。 The code I'm going to post is supposed to take only the first word and print it out on the screen. 我要发布的代码应该仅使用第一个单词并将其打印在屏幕上。 When I run it, it doesn't print anything. 当我运行它时,它不会打印任何内容。 I thought that maybe I did something wrong in the while loop so I did a simple test. 我以为也许我在while循环中做错了什么,所以我做了一个简单的测试。 Let's say my input is "This is a test sentence" and instead of word (in cout), I type word[0]. 假设我的输入是“这是一个测试句子”,而不是单词(在cout中),我键入word [0]。 Then it prints "T" just fine. 然后打印“ T”就好了。 Can you find what the problem is? 您能找到问题所在吗?

#include <iostream>
#include <string>
using namespace std;

int Letters(string str) {
    int i=0;
    int len=str.length();
    string word;
    while(i<len){
        if(isspace(str[i])){word[i]='\0'; break;}
        word[i]=str[i];
        i++;
    }
    cout<<word;
    return 0;
}

int main() {
    int test;
    string str;
    getline(cin, str);
    test=Letters(str);
    return 0;
}
string word;

is default constructed, which is empty initially. 是默认构造的,最初为空。 Inside while loop, you tried to do: while循环内,您尝试执行以下操作:

word[i] = str[i];

It means you tried to access memory that has not been allocated,resulting in undefined behavior . 这意味着您试图访问未分配的内存,导致未定义的行为

Try: 尝试:

word.append(str[i]); 

You can use simpler way to get words from input in C++. 您可以使用更简单的方法从C ++输入中获取单词。 It will help you to avoid errors in the future. 这将帮助您避免将来出现错误。

#include <iostream>
using namespace std;

int main()
{
  string word;
  while(cin >> word)
    {
      // "word" contains one word of input each time loop loops
      cout << word << endl;
    }
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM