2013-03-30 17 views
0

我真的很想幫助我的一個項目。我是一名平面設計的學生,幾乎沒有編程經驗。我創建了一個熱敏迷你打印機的程序,根據所使用的特定標籤標識在Twitter上製作鳴叫,並自動打印。在Thermo迷你打印機上使用C語言編寫文本

但是,它基於32個字符的行長度,並將單詞分成一半而不是將整個單詞移動到另一行。我的一個朋友建議換行,但我找不到任何在線幫助我,我發現的大多數代碼都傾向於C++或c#。

到目前爲止的代碼可以發現如下:

// Build an ArrayList to hold all of the words that 
// we get from the imported tweets 

ArrayList<String> words = new ArrayList(); 
Twitter twitter; 
import processing.serial.*; 

Serial myPort; // Create object from Serial class 
int val;  // Data received from the serial port 

void setup() { 
    String portName = Serial.list()[0]; 
    myPort = new Serial(this, portName, 9600); 
    //Set the size of the stage, and the background to black. 
    size(550,550); 
    background(0); 
    smooth(); 

    //Make the twitter object and prepare the query 
    twitter = new TwitterFactory(cb.build()).getInstance(); 
} 

void draw() { 

    Query query = new Query("#R.I.P"); 
    query.setRpp(1); 

    //Try making the query request. 
    try { 
     QueryResult result = twitter.search(query); 
     ArrayList tweets = (ArrayList) result.getTweets(); 

     for (int i = 0; i < tweets.size(); i++) { 
      Tweet t = (Tweet) tweets.get(i); 
      String user = t.getFromUser(); 
      String msg = t.getText(); 
      Date d = t.getCreatedAt(); 
      println("Tweet by " + user + " at " + d + ": " + msg); 
      msg = msg.replace("\n"," "); 
      myPort.write(msg+"\n"); 
     }; 
    } 
    catch (TwitterException te) { 
     println("Couldn't connect: " + te); 
    }; 
    println("------------------------------------------------------"); 
    delay(20000); 
} 

回答

0

既然你的線的長度,它並不難......

遍歷字符串,一個字符時。如果您看到一個空格,則將位置保存爲例如last_space。如果迭代超過最大線長,則轉到last_space位置並將空間轉換爲換行符,將位置計數器重置爲零,然後從該位置重新開始。


可能實現它是這樣的:

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 

#define LINE_LENGTH 32 

char text[256] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ac risus elit, id pellentesque magna. Curabitur tempor rutrum enim, sit amet interdum turpis venenatis vel. Praesent eu urna eros. Mauris sagittis tempor felis, ac feugiat est elementum sed. Praesent et augue in nibh pharetra egestas quis et lectus. Lorem ipsum."; 

static void wrap(char *text, const int length) 
{ 
    int last_space = 0; 
    int counter = 0; 

    for (int current = 0; text[current] != '\0'; current++, counter++) 
    { 
     if (isspace(text[current])) // TODO: Add other delimiters here 
      last_space = current; 

     if (counter >= length) 
     { 
      text[last_space] = '\n'; 
      counter = 0; 
     } 
    } 
} 

int main(void) 
{ 
    printf("Before wrap:\n%s\n", text); 

    wrap(text, LINE_LENGTH); 

    printf("\nAfter wrap:\n%s\n", text); 

    return 0; 
} 

重要事項:wrap函數修改傳入的參數text緩衝區。這意味着它不能處理字符串,因爲它們是隻讀的。它的工作原理是用換行符替換一個空格。如果修改該函數以添加多個字符,則更好的解決方案將通過(重新)分配一個足夠容納修改字符串的新緩衝區。

+0

嗨,我明白你的意思,但由於我的小編程知識,可惜我不知道如何實現這一點。 –

+0

@LizHamburger添加了示例程序以顯示如何完成。 –

+0

感謝這個例子,但是我不知道它會發生什麼或者我應該替換什麼文本 –